Section 13.12. Processing Exceptions


13.12. Processing Exceptions

Catch exception objects in most-derived-first order.

The only drawback to using method calls to detect particular types of exceptions:

      if ( X::TooBig->caught(  ) ) {

is that you have to be careful about the order in which you try your alternatives. For example, if X::WaaaaayTooBig inherits from X:TooBig, the following code won't work correctly:

      
     # If the attempt fails...
if ($EVAL_ERROR) {
# If the candidate was considered too big, go with the maximum allowed...
if ( X::TooBig->caught( ) ) { my @range = $EVAL_ERROR->get_range( ); $value = $range[-1]; }
# If the candidate was considered waaaaay too big, rethrow the exception...
elsif ( X::WaaaaayTooBig->caught( ) ) { $EVAL_ERROR->rethrow( ); }
# etc.
}

The problem is that if an X::WaaaaayTooBig exception is thrown, $EVAL_ERROR will refer to an X::WaaaaayTooBig object. But the X::WaaaaayTooBig class inherits from the X::TooBig class, so an X::WaaaaayTooBig object is an X::TooBig object. That means the first if test will succeed, and the specialized derived-class exception will be treated like a generic base-class exception instead.

The solution is simple: whenever you're determining the type of an exception you just caught, test for the most-derived classes first.



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net