What’s broken about exceptions in Perl?

The typical method most people have learned to handle exceptions is vulnerable to missing trapped exceptions:

eval { some code here };
if( $@ ) {  handle exception here };

You can do:

eval { some code here; 1 } or do { handle exception here };

This protects from missing the exception due to $@ being clobbered, but it is still vulnerable to losing the value of $@.

To be sure you don’t clobber an exception, when you do your eval, you have to localize $@;

eval { local $@; some code here; 1 } or do { handle exception here };

This is all subtle breakage, and prevention requires a lot of esoteric boilerplate.

In most cases this isn’t a problem. But I have been burned by exception eating object destructors in real code. Debugging the issue was awful.

The situation is clearly bad. Look at all the modules on CPAN built provide decent exception handling.

Overwhelming responses in favor of Try::Tiny combined with the fact that Try::Tiny is not “too clever by half”, have convinced me to try it out. Things like TryCatch and Exception::Class::TryCatch, Error, and on and on are too complex for me to trust. Try::Tiny is a step in the right direction, but I still don’t have a lightweight exception class to use.

Leave a Comment