views:

89

answers:

1

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?

+8  A: 

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:

  • Perl not being a fully object-oriented language. (e.g. in contrast to Java where you can't avoid dealing with exceptions.)
  • The background of many Perl developers. (Languages like C1 and shell don't have exception mechanisms.)
  • The kind of tasks people tend to use Perl for. (Small scripts for text munging and report generation where exception handling isn't needed.)
  • Perl not having a (good) built-in exception mechanism.

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.

Michael Carman
+1 "make it *easier* to get right"
pst
And just to clear up a common misconception which the original poster might or might not suffer from: `eval BLOCK` is *not* `eval STRING` and doesn't compile code at runtime. It's just an exception-handling method -- `try` with a funny name and slightly funny semantics.
hobbs