3

I have a SOAP client written in Perl using LWP package for the HTTPS transport and XML::Simple for the parsing of the XML payloads. From time to time the call to XMLin fails with a die() and then my script dies and has to be restarted by a monitoring program that I have written to detect this. This is really not desirable, and so I was wondering if Perl has any facility like the C++ exception handling mechanism where I can catch the die message, ignore it report the error and let my script continue just as if an error occurred? I have read a number of Perl books and looked for this but I have not managed to find something. This is killing my application but I dont want to write my own XML parsing code unless I absolutely have to.

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
  • Use a high-level SOAP library such as [SOAP::Lite](http://p3rl.org/SOAP::Lite) that comes with its own error handlers. – daxim Jul 03 '12 at 19:44

2 Answers2

7

Yes; the basic mechanism for doing this would be an eval:

sub a { die "BAD"; }
eval { a(); }
print "Survived an exception $@";

However, there are reasons why you should use more high-level constructs (which are nevertheless constructed on top of this), like Try::Tiny et al. (see the links at the bottom of its documentation).

jpalecek
  • 47,058
  • 7
  • 102
  • 144
-2

You can catch the "die" but you can't stop your script from dying by catching it: *When a "__DIE__" hook routine returns, the exception processing continues as it would have in the absence of the hook, unless the hook routine itself exits via a "goto", a loop exit, or a "die()".*

You can run the routines which are susceptible to call the die() inside an eval{} block, though.

fork0
  • 3,401
  • 23
  • 23
  • So essentially then my script will terminate whenever the package encounters a condition that calls die() ?? There is nothing I can do at all? Oh well looks like I better start the C++ version.... – mathematician1975 Jul 03 '12 at 19:24
  • well yes, except for that eval of which you have been told twice now – fork0 Jul 03 '12 at 19:44