http://qs1969.pair.com?node_id=486396


in reply to Exception::Class - how to use?

Arunbear's answer is a good one. I'd add that you want to be sure you know why you want to use Exception::Class. If you aren't planning to handle various exceptions, you almost might as well define some standard error messages and just die with them -- but then the major advantage of Exception::Class is that it's easier/saner/maintainable to determine what type of error occured from an object type than from parsing the error message.

You want to consider the right place to use eval. Do you want to:

You should wrap routines with eval when you either know what the fallback behavior should be or you need to exit more gracefully than just allowing the program to die. (That's all the throw is -- just a die with an Exception::Class object instead of an error message.) And you want to wrap it at the right point for the error to be handled. That means probably not wrapping every little call, but rather wrapping as high up in the calling stack as possible:

use Exception::Class::TryCatch; sub user_input_loop() { USER_INPUT: while ( my $line = <> ) { # try the command eval { process_command( $line ) }; # catch any error if( catch my $err ) { if( $err->isa('MyErr::Recoverable') ) { warn "Input error: $err\n"; next USER_INPUT; } else { # not recoverable warn "Unrecoverable error: $err\n"; $err->rethrow; } } } print "Exiting normally\n"; }

You want to leave it to your end-users when the right thing to do in response to an error condition is up to them. Or you can stage it: catch the exception, do some cleanup, then rethrow the exception.

It's not really much of a contortion if you consider what an alternative might be. If an end-user wants to know why some eval died, their only other option is to examine the $@ as a string. That's requires similar contortions and probably breaks the moment you change one of your error messages.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Replies are listed 'Best First'.
Re^2: Exception::Class - how to use?
by rvosa (Curate) on Aug 25, 2005 at 10:54 UTC
    Thank you both for your clarifications - that's very helpful. I think I am just going to have to think hard in each situation whether I want to catch exceptions myself or leave it to the user. I suppose it depends, in some cases I might be able to do something gracefully, but in other cases the user is going to have to be told forcefully that their input isn't sane. I don't suppose there's a hard and fast rule for that, is there?