Perl Information Center Tutorials - Exceptions
These tutorials were written to help you get a quick, but thorough, understanding of Perl -
the scope of the language as well as it's specific capabilities.
| Beginners
| Built-In Functions
| Advanced
| CGI Applications
|
|
|
|
|
|
Exception Functions Summary
When Perl detects an error it attempts to work around the error and
continue execution. If it cannot resolve the problem, Perl displays
an error message and stops execution of the script.
Alternately, the following three functions may be used to modify how errors
are handled. Generally, these functions allow a custom error message to
be displayed in addition to, or in place of, the default Perl error messages.
The functions also allow the program to decide whether to terminate the program.
Exception Functions Syntax
Here are the basic ways in which the die function can be used to
respond to an error message.
1 open (INFILE, "input.txt");
2 open (INFILE, "input.txt") || die;
3 open (INFILE, "input.txt") || die "Bad file";
4 open (INFILE, "input.txt") || die "Bad file \n";
5 open (INFILE, "input.txt") || die "Bad file \n $!";
The effect of each lines is discussed below, on the assumption that
the file 'input.txt' is not found.
If the warn function is used in place of the die function, the same
messages are displayed but program execution does not stop.
Eval Function Syntax
Perl also provides a way to trap errors - to prevent them from terminating
the program and to allow the programmer to decide what action to take.
Consider the following lines of code.
1 $a/$b
2 eval{$a/$b};
3 if ($@) {print "Error occurred: $@. Program will continue!"}
Line 1 will crash a program is $b has a value of zero.
Line 2 shows that wrapping the code in a block labelled 'eval' will trap
the error and Perl will not terminate the program. The error message will
be placed in the special variable $@. If there was no error, then $@ will
be empty.
Exception Function Reference
Here's a quick reference of the available exception functions, in alphabetical
order.
- die - return an error message, then raise an exception
die LIST
- eval - catch exceptions
eval EXPR
- warn - return an error message (does not raise an exception)
warn LIST
- $! - returns either the error number or the error message of the
last operations, depending on whether used in scalar or string context.
It only contains valid data immediately after a failed system request.
- $@ - the syntax error or routine error message from the last eval,
If set, either the compilation failed, or the die function was executed
within the code of the eval.
If you have any suggestions for additions to these tutorials, please let me know.
|