{ my %dispatch_error; BEGIN { %dispatch_error = ( TypeError => sub { ... handle TypeError exceptions ... }, RangeError => sub { ... handle RangeError exceptions ... } +, ..., '' => sub { ... handle any unspecified exceptions ... }, ); } sub handle_error { my ($e) = @_; my $error_type = ref $e; $error_type = '' unless exists $dispatch_error{$error_type}; $dispatch_error{$error_type}->($e); return; } } try { myroutine(); } catch { handle_error($_); };
One obvious disadvantage is that you need a different handle_error() routine for each different set of exceptions you want to handle. Also, the exception handling code moves away from the catch. And the exception handlers might be outside the scope of the try-catch-block (they aren't, in your example), so they don't have access to local variables.
How would you solve this?
# not quite Perl sub work { # Handle a few exceptions my $result1; try { $result1=doSomeMath(); } catch (DivByZeroException) { $result1="div by 0"; } catch (NotANumberException) { $result="not a number"; } # no explicit handler for other exceptions, so re-throw # Handle a different set of exceptions my $result2; try { $result2=doSomeMoreMath(); } catch (DivByZeroException) { $result2="div by 0"; } # no check for NaN, will be re-thrown like any other Exception h +ere # Handle all possible exceptions, with a special handling for one +exception try { writeToFile($result1,$result2); } catch (IOException) { say "oopsie - I/O problem"; } catch { say "something else went wrong"; } }
Alexander
In reply to Re^2: conditional catch-blocks 'try {} catch(COND) { }'
by afoken
in thread conditional catch-blocks 'try {} catch(COND) { }'
by LanX
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |