I've noticed that Exception.pm and Error.pm don't seem to be extensively used in the Perl community. Is that due to the large footprint of eval
for exception handling?
Also Perl programs appear to have a much more lenient policy regarding exception handling in general. Is there a compelling reason for this?
In any event what would be the best method for exception handling in Perl?
If an exception occurs within the try block, then it is handled by the appropriate exception handler (catch block), associated with the try block. If no exceptions are thrown, then try will return the result of block. A try block should have at least one (or more) catch block(s) or one finally block.
The try and catch block of code is used for error handling in Perl, similar to other languages such as Java and Python. The try and catch block tries the code meant to be executed in the try block, and if an error occurs, the program does not crash.
$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.
The consensus of the Perl community seems to be that Try::Tiny is the preferred way of doing exception handling. The "lenient policy" you refer to is probably due to a combination of:
Note that the last item means that you'll see a lot of code like this:
eval { something() }; if ($@) { warn "Oh no! [$@]\n"; }
That's exception handling even though it doesn't use try/catch syntax. It's fragile, though, and will break in a number of subtle edge cases that most people don't think about. Try::Tiny and the other exception handling modules on CPAN were written to make it easier to get right.
1. C does have setjmp()
and longjmp()
, which can be used for a very crude form of exception handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With