Error Handlers In Perl
Contents |
Perl IF..ELSE.. Perl Loopings Perl Operators Perl Files & I/O Regular Expressions Perl Subroutines Perl Formats Perl Error Handling Perl Coding Standard Advanced PERL Perl Sockets Writing Perl Modules Object Oriented Perl Database Management CGI Programming PERL References Perl Functions Selected Reading
File Handlers In Perl
Computer Glossary Who is Who Copyright © 2014 by tutorialspoint Home References About TP perl error handling Advertising Error Handling in PERL Advertisements You can identify and trap an error in a number of different ways. Its very easy
Perl Error Handling Eval
to trap errors in Perl and then handling them properly. Here are few methods which can be used. Using if The if statement is the obvious choice when you need to check the return value from a perl error handling best practices statement; for example: if (open(DATA,$file)) { ... } else { die "Error: Couldn't open the file $!"; } Here variable $! returns the actual error message Alternatively, we can reduce the statement to one line in situations where it makes sense to do so; for example: die "Error: Something went wrong\n" if (error()); Using unless The unless function is the logical opposite to if: statements can completely bypass the success status and only be perl catch error executed if the expression returns false. For example: unless(chdir("/etc")) { die "Error: Can't change directory!: $!"; } The unless statement is best used when you want to raise an error or alternative only if the expression fails. The statement also makes sense when used in a single-line statement: die "Error: Can't change directory!: $!" unless(chdir("/etc")); Here we die only if the chdir operation fails, and it reads nicely. Using the Conditional Operator For very short tests, you can use the conditional operator: print(exists($hash{value}) ? 'There' : 'Missing',"\n"); It's not quite so clear here what we are trying to achieve, but the effect is the same as using an if or unless statement. The conditional operator is best used when you want to quickly return one of two values within an expression or statement. The Warn Function The warn function just raises a warning, a message is printed to STDERR, but no further action is taken. chdir('/etc') or warn "Can't change directory"; The Die Function The die function works just like warn, except that it also calls exit. Within a normal script, this function has the effect of immediately terminating execution. chdir('/etc') or die "Can't change directory"; Reporting Errors Within Modules There are two different situations we need to be able to handle: Reporting an error in a module th
Perl and how to implement it using Error.pm. On our way, we'll be touching upon the advantages of using exception-handling over traditional error-handling mechanisms, exception handling with eval {}, problems with eval {} and the functionalities
Perl Error Trapping
available in Fatal.pm. But by and large, our focus we'll be on using Error.pm for perl dbi error handling exception handling. What Is an Exception ? An exception can be defined as an event that occurs during the execution of a program
Perl System Error Handling
that deviates it from the normal execution path. Different types of errors can cause exceptions. They can range from serious errors such as running out of virtual memory to simple programming errors such as trying to read http://www.tutorialspoint.com/perl/perl_error_handeling.htm from an empty stack or opening an invalid file for reading. An exception usually carries with it three important pieces of information: The type of exception - determined by the class of the exception object Where the exception occurred - the stack trace Context information - error message and other state information An exception handler is a piece of code used to gracefully deal with the exception. In the rest of article, the terms exception http://www.perl.com/pub/2002/11/14/exception.html handler and catch block will be used interchangeably. By choosing exceptions to manage errors, applications benefit a lot over traditional error-handling mechanisms. All the advantages of using exception handling are discussed in detail in the next section. Advantages of Using Exception Handling Object-oriented exception handling allows you to separate error-handling code from the normal code. As a result, the code is less complex, more readable and, at times, more efficient. The code is more efficient because the normal execution path doesn't have to check for errors. As a result, valuable CPU cycles are saved. Another important advantage of OO exception handling is the ability to propagate errors up the call stack. This happens automatically without you, the programmer, explicitly checking for return values and returning them to the caller. Moreover, passing return values up the call stack is error prone, and with every hop there is a tendency to lose vital bits of information. Most of the time, the point at which an error occurs is rarely the best place to handle it. So, the error needs to be propagated up the call stack. But by the time the error reaches the place where it can be handled suitably, a lot of the error context is lost. This is a common problem with traditional error-handling mechanisms (i.e. checking for return values and propagating the
The remote host or network may be down. Please try the request again. Your cache administrator is webmaster. Generated Mon, 10 Oct 2016 01:56:44 GMT by s_ac5 (squid/3.5.20)
Q&A Tutorials Poetry RecentThreads NewestNodes Donate What'sNew on Sep 27, 2014 at 11:31UTC ( #1102209=perlquestion: print w/replies, xml ) Need Help?? v_melnik has asked for the wisdom of the Perl Monks concerning the following question: Dear colleagues, I think, it's a matter of religion, but I'd like to get to know more on how other people, more experienced, prefer to handle errors/exceptions in respect to the structure of your programs. Let me describe how I'm doing it now and, if you have some time to share your experience, I'd be very grateful to you for describing how do you prefer to do it. My own "rules" for myself are quite simple. Don't die() while executing a subrotine or method. Only the main module can die() if something goes wrong. Nobody can predict where the class will be used, so an unexpected die() can break the caller's logic. If I've got an exception inside of a subroutine, the subroutine may return(undef). If everything's fine, it return's some value (it can be true or false - no matter), but if some error has been occuried (e.g. if we can't get data from the database), the undef shall be returned. That's okay, but how to let the caller know what's happened with the subroutine? As I think, the caller must have some explaination to be able to write something to the log-file or to show the error message to the operator. So, there is one more rule. Any class may have the "errstr" attribute, so if its' methor returned undef, the caller may get the explaination from this attribute. So, usually it looks like this: package SomeClass; #... sub some_method { # ... eval { die("Oops!"); }; if($@) { $self->{'errstr'} = "Something has gone wrong: $@"; return(undef) } # ... } #... package main; #... my $result = $obj->some_method; unless(defined($result)) { die("Can't SomeClass->some_method(): $obj->{'errstr'}"); } #... [download] And, when something goes wrong, I can get something like that: Can't SomeClass->some_method(): Can't AnotherClass->another_method(): Can't OtherClass->other_method(): Can't open(): No such file at script.pl line 666. Frankly speaking, I have a persistent feeling that there are some other, much m