Handling Exceptions
Problem
How do you safely call a function that might raise an exception? How do you create a function that raises an exception?
Solution
Sometimes you encounter a problem so exceptional that merely
returning an error isn’t strong enough, because the caller
could ignore the error. Use
die
STRING from your
function to trigger an exception:
die "some message"; # raise exception
The caller can wrap the function call in an eval
to intercept that exception, and then consult the special variable
$@ to see what happened:
eval { func() };
if ($@) {
warn "func raised an exception: $@";
}Discussion
Raising exceptions is not a facility to be used lightly. Most
functions should return an error using a bare
return statement. Wrapping every call in a trap is
tedious and unsightly, removing the appeal of using exceptions in the
first place.
But on rare occasion, failure in a function should cause the entire
program to abort. Rather than calling the irrecoverable
exit function, you should call
die instead, which at least gives the programmer
the chance to cope. If no exception handler has been installed via
eval, then the program aborts at that point.
To detect such a failure program, wrap the call to the function with
a block eval. The $@ variable
will be set to the offending exception if one occurred; otherwise, it
will be false.
eval { $val = func() };
warn "func blew up: $@" if $@;Any eval catches all exceptions, not just specific ones. Usually you should propagate unexpected ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access