Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Exception catching sub

by bsb (Priest)
on Sep 02, 2003 at 08:57 UTC ( #288267=snippet: print w/replies, xml ) Need Help??
Description: The "catch" sub below handles $@ after an eval { }.

I just came up with this today, so it's relatively untested and up for criticism.

PS. I know about Error.pm's funky extension syntax but the problems worry me.

# called just after an eval
sub catch {
  # don't catch if no error
  return 0 unless defined $@;
  
  # checks if $@->isa(one of the type in @_);
  UNIVERSAL::isa($@,$_) && return 1 for @_;
  
  # otherwise re-throws
  die $@;
}

# later on ...
while (my ($name,$val) = each %input) {
  if(eval { validate($val) }) { 
    $session->set($name, $val);

  } elsif(catch('ARRAY','E')) { 
    $errors{$name} = $@;        
    $action = 'reshow';
  } 
} 

# ...
eval { $nav->$action() } 
  or catch('E::Nav') and do { $error = $@; $nav->reshow };

# ... other things I haven't thought of ...

Replies are listed 'Best First'.
Re: Exception catching sub
by simonm (Vicar) on Sep 02, 2003 at 18:28 UTC
    Automatically rethrowing (die $@) prevents you from catching several different types of exceptions in a series of elsifs -- I think you probably only want to rethrow if none of your catches match: if ( eval ... ) { ... } elsif ( catch("E") ) { ... } elsif ( catch("F") ) { ... } else { die $@; }
      Good point. Thanks.
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://288267]
help
Chatterbox?
[marioroy]: LA https://unix. stackexchange.com/ questions/81349/ how-do-i-use-find- when-the-filename- contains-spaces
[Lady_Aleena]: marioroy, I figured it out.
[marioroy]: LA find -printf ...
[marioroy]: Lady_Aleena++

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2017-04-23 23:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I'm a fool:











    Results (433 votes). Check out past polls.