Exception handling syntax: Difference between revisions

Content deleted Content added
Perl: expand entry using Matt Sergeant's presentation "Exception Handling in Perl" -
Line 262:
* see also [[Vectored Exception Handling]] (VEH).
 
===[[ Perl]] ===
The [[Perl]] mechanism for exception handling uses <tt>die</tt> to throw an exception when wrapped inside an <tt>eval { ... };</tt> block. After the <tt>eval</tt>, the special variable <tt>$@</tt> contains the value passed from <tt>die</tt>.
<source lang=perl>
 
<source lang="perl">
eval {
# Code that could throw an exception (using 'die')
open(FILE, $file) || die "Could not open file: $!";
while (<FILE>) {
process_line($_);
}
close(FILE) || die "Could not close $file: $!";
};
if ($@) {
# Handle exception here. (The exception objectstring is in $@)
}
</source>
 
Perl 5.005 added the ability to throw objects as well as strings. This allows for better introspection and handling of types of exceptions.
 
<source lang="perl">
eval {
open(FILE, $file) || die MyException::File->new($!);
while (<FILE>) {
process_line($_);
}
close(FILE) || die MyException::File->new($!);
};
if ($@) {
# The exception object is in $@
if ($@->isa('MyException::File')) {
# Handle file exception
} else {
# Generic exception handling
# or re-throw with 'die $@'
}
}
</source>
 
The <tt>__DIE__</tt> pseudo-signal can be trapped to handle calls to <tt>die</tt>. This is not suitable for exception handling since it is global. However it can be used to convert string-based exceptions from third-party packages into objects.
 
<source lang="perl">
local $SIG{__DIE__} = sub {
my $err = shift;
if ($err->isa('MyException')) {
die $err; # re-throw
} else {
# Otherwise construct a MyException with $err as a string
die MyException::Default->new($err);
}
};
</source>
 
A number of modules in [[CPAN]] expand on the basic mechanism:
* <tt>Error</tt> provides a set of exception classes and allows use of the try/throw/catch/finally syntax.
* <tt>Exception::Class</tt> is a base class and class-maker for derived exception classes. It provides a full structured [[stack trace]] in <tt>$@->trace</tt> and <tt>$@->trace->as_string</tt>.
* <tt>Fatal</tt> overloads previously defined functions that return true/false e.g open, close, read, write, etc. This allows built-in functions and others to be used as if they threw exceptions.
 
=== [[PHP]] ===