#! perl -slw use strict; sub divide { my( $e, $d ) = @_; return $e / $d; } my $result = eval{ divide( @ARGV ) } or die $@; print "Result: $result"; #### __END__ C:\test>NoExceptions Use of uninitialized value $d in division (/) at C:\test\NoExceptions.pl line 6. Use of uninitialized value $e in division (/) at C:\test\NoExceptions.pl line 6. Illegal division by zero at C:\test\NoExceptions.pl line 6. C:\test>NoExceptions A B Argument "B" isn't numeric in division (/) at C:\test\NoExceptions.pl line 6. Argument "A" isn't numeric in division (/) at C:\test\NoExceptions.pl line 6. Illegal division by zero at C:\test\NoExceptions.pl line 6. C:\test>NoExceptions 1 Use of uninitialized value $d in division (/) at C:\test\NoExceptions.pl line 6. Illegal division by zero at C:\test\NoExceptions.pl line 6. C:\test>NoExceptions 1 0 Illegal division by zero at C:\test\NoExceptions.pl line 6. C:\test>NoExceptions 1 2 Result: 0.5 #### #MyExceptions.pm package MyExceptions; use Exception::Class ( 'MyException', 'AnotherException' => { isa => 'MyException' }, 'YetAnotherException' => { isa => 'AnotherException', description => 'These exceptions are related to IPC' }, 'ExceptionWithFields' => { isa => 'YetAnotherException', fields => [ 'grandiosity', 'quixotic' ], alias => 'throw_fields', }, ); 1; ## Exceptions.pl #! perl -slw use strict; use MyExceptions; sub divide { my( $e, $d ) = @_; MyExceptions->throw( error => 'Divisor undefined' ) unless defined $d; MyExceptions->throw( error => 'Divisor is zero' ) if $d == 0; return $e / $d; } # try my $result = eval { divide( @ARGV ) }; my $e; # catch if ( $e = Exception::Class->caught('MyException') ) { die 'You must supply two arguments' if $e->error eq 'Divisor undefined'; die 'The second argument must not be zero' if $e->error eq 'Divisor is zero'; die sprintf "Unanticipated exception: '%s' at \n%s\n", $e->error, $e } else { $e = Exception::Class->caught(); ref $e ? $e->rethrow : die $e; } #### #! perl -slw use strict; use Carp; use Try::Tiny; use constant { ERROR123 => 'Divisor is undefined', ERROR456 => 'Divisor is zero', }; sub divide { my( $e, $d ) = @_; croak ERROR123 unless defined $d; croak ERROR456 if $d == 0; return $e / $d; } my $result; try{ $result = divide( @ARGV ); } catch { die "You forgot to supply the second argument\n" if $_ =~ ERROR123; die "Dividing anything by zero is infinity\n" if $_ =~ ERROR456; die "Unknown error $_\n"; }; print "Result: $result"; #### __END__ C:\test>Exceptions-TryTiny You forgot to supply the second argument C:\test>Exceptions-TryTiny A B Argument "B" isn't numeric in numeric eq (==) at C:\test\Exceptions-TryTiny.pl line 14. Dividing anything by zero is infinity C:\test>Exceptions-TryTiny 1 You forgot to supply the second argument C:\test>Exceptions-TryTiny 1 0 Dividing anything by zero is infinity C:\test>Exceptions-TryTiny 1 2 Result: 0.5