tags:

views:

136

answers:

2

In my application, I use XML::Simple and use the exported XMLin() to parse XML files. Everything goes well until an invalid file path is used as the parameter for XMLin().

The application is terminated because XML::Simple used die() or some similar method when it was given an invalid file path.

I want my app to continue running even though XML::Simple met a fault. So what should I do?

+3  A: 

Wrap the call in a block eval:

eval {
  do_stuff_that_might_die();
  1;
} or do {
  # Only executes if the call died, in case you want
  # to do any cleanup or error handling
  print "It died, but life goes on!\n";
}; # <-- Don't forget the semicolon!
Dave Sherohman
Your sample is good, except that if `do_stuff_that_might_die()` returns a false value, then your error message is incorrect. You can add a `1;` at the end of your eval to fix that.
daotoad
Oh, good point - thanks for catching that! I've edited the code to add this.
Dave Sherohman
+5  A: 

Handle the exception.

General way:

use English qw( -no_match_vars );

eval {
    run_your_code_that_might_die();
};

if ( my $error = $EVAL_ERROR ) {
    die $error unless $error =~ m{some|known|error};
    handle_known_error( $error );
}

English in there is only so I can use $EVAL_ERROR instead of $@.

Generally, check perldoc for eval function.

depesz
+1 even though I hate `English.pm` with a passion.
Sinan Ünür
@Sinan - why? I'm curious, no harm/trolling intended :)
depesz
Robert P
@Robert - not sure if what you write is to "dislike English" or to "like English". Descriptive names are very good, and the issue with regexps is mentioned every time when English is.
depesz
@depesz I first learned the short, so-called non-descriptive, names of built-in variables. I cannot remember the mapping of those names to the so-called descriptive names used by English. Purely subjective, of course, but any section of code that has a lot of capital letters turns me off.
Sinan Ünür
Your eval trapping code can miss eval failures. You need an atomic check like Dave Sherohman has in his code. See http://www.perlfoundation.org/perl5/index.cgi?exception_handling
daotoad
See Acme::ExceptionEater (http://search.cpan.org/dist/Acme-ExceptionEater/lib/Acme/ExceptionEater.pm) for an example of code that breaks your eval error trapping. For more detail on A::EE, see http://perlmonks.org/?node_id=637764
daotoad