Perl exception handling

I've been working on a Perl module that makes sending email messages a breeze, but one problem I had is that the Perl module MIME::Lite has a nasty way of failing when something goes wrong. I could not "catch" it's errors with die or warn, so after a little research, I found out how to deal with this problem using eval. According to one text, using eval is the only mechanism Perl has for exception handling.

Here's what I was doing that didn't work:

$msg->send || die ""

(where $msg is a reference to a MIME::Lite object). Whenever an SMTP error occurred, my program stopped completely, which is obviously very bad, especially when you're running inside a loop, trying to send an email to 7,000 subscribers.

Here's the code that fixed the problem:

eval { $msg->send; }; warn $@ if $@;

The eval function let me trap the error being thrown by the MIME::Lite code, print an error message with the warn $@ if $@ syntax, and most importantly, keep my program running.

I'm not an expert on this yet, but at least it's something to let me deal with simple exceptions like this.

 

Permalink

This solution is awesome.... This gives me a great relief in exception handling in my Perl code.

Thanks

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.