Handling Exceptions


How do you safely call a function that might raise an exception? How do you create a function that raises an exception?


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: $@";


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 ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.