in reply to Catching a 'division by zero' error with Exception::Class

Before going into Exception classes, you might want to play with eval without the Exception classes. Get familliar with how perl handles exceptions before doing anything else.

EG

eval { die "woot!\n" }; if ( $@ =~ /woot/ ) { die "This is a 'woot' error!\n" } else { die $@; }

If you're not familiar, eval {} and eval "" are totally different animals, so watch out for that confusion. eval {} is really like a try block in most other languages. eval "" is like eval in other languages.

Replies are listed 'Best First'.
Re^2: Catching a 'division by zero' error with Exception::Class
by ggvaidya (Pilgrim) on Sep 16, 2008 at 04:47 UTC

    I completely agree, eval-die is flexible enough for most use. Is there any advantage with hierarchical exceptions which is worth the addition code and modules?

    The original problem can be written as:

    use warnings; use strict; use 5.0100; eval { print 10/0; # equivalent to: die "Illegal division by zero"; }; if($@) { if($@ =~ /Illegal division by zero/) { print "I feel funny\n"; exit; } else { die $@; } } # No exception thrown. print "What do you know, Perl can divide by zero.\n";

    Updated: this code doesn't work properly before Perl 5.10, so I added a 'use' statement to stop it.

      I hope it's helpful to someone to point out that your solution works in 5.10.0 but in 5.8.8 perl dies with the familiar "Illegal division by zero at foo line 5." error.

      In fact, pasting that into perl 5.8.8's standard input instead of putting it in a file exits the shell in which it was run. That may not be the sort of thing people appreciate from example code.

        Thanks for pointing that out! I've put a "use 5.10" line in so it won't run unchanged on pre-5.10 perls. Do you think that's good enough?