10.12. Handling ExceptionsProblemHow 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 "some message"; # raise exception
The caller can wrap the function call in an 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
But on rare occasion, failure in a function should cause the entire program to abort. Rather than calling the irrecoverable
To detect such a failure program, wrap the call to the function with a block eval { $val = func() }; warn "func blew up: $@" if $@;
Any eval { $val = func() }; if ($@ && $@ !~ /Full moon!/) { die; # re-raise unknown errors }
If the function is part of a module, consider using the Carp module and call Another intriguing possibility is for the function to detect that its return value is being completely ignored; that is, it is being called in a void context. In that case, returning an error indication would be useless, so raise an exception instead. Of course, just because it's not voided doesn't mean the return value is being dealt with appropriately. But if it is voided, it's certainly not being checked. if (defined wantarray()) { return; } else { die "pay attention to my error!"; } See Also
The
|
|