in reply to Re: conditional catch-blocks 'try {} catch(COND) { }'
in thread conditional catch-blocks 'try {} catch(COND) { }'
{ 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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: conditional catch-blocks 'try {} catch(COND) { }'
by choroba (Cardinal) on Sep 20, 2021 at 19:50 UTC | |
by afoken (Chancellor) on Sep 21, 2021 at 11:29 UTC | |
by LanX (Saint) on Sep 21, 2021 at 11:39 UTC | |
by afoken (Chancellor) on Sep 21, 2021 at 18:54 UTC | |
by LanX (Saint) on Sep 21, 2021 at 21:33 UTC | |
by LanX (Saint) on Sep 21, 2021 at 13:16 UTC | |
|
Re^3: conditional catch-blocks 'try {} catch(COND) { }'
by kcott (Archbishop) on Sep 20, 2021 at 14:42 UTC |