Perl Exception Handling

What Is Exception Handling?

In it’s simplest form, Exception Handling allow you to write a block of code and wrap it in your own form of error handling. Typically a program will attempt to accomplish a number of tasks and then report to you the status of those tasks or produce an error. However, often when writing a program you do not want your program to die immediately when an error occurs as you may be able to handle those errors. This is what Exception Handling does for you. It is a programming construct designed to handle an error caused at runtime.

For those of you that understand how transactions work in a RDBMS, it’s the same principle. You can attempt to execute a chunk or block of code (or SQL statements) and if an error occurs somewhere, you can catch it (or in the SQL-world, rollback).

Here’s an example of a typical program that initiates a database connection, tries to do something and then inserts some data.

#!/usr/bin/perl -w

use strict;
use DBI;

my $dbh = DBI->connect('DBI:mysql:dbname', 'user', 'pass')
  or die "cannot connect to db";

# With the db command, do stuff..
my $id = connectToWebService('twitter', 'send', '@bob, Hi')
  or die "connectToWebService() failed for twitter...";

# Insert the $id->{'twitid'}, $id->{'msg'} into the database
...

print "success!\n";

It’s a simple enough script to understand. The connectToWebService() function is just a fake function I made up for our example. If it fails, it will terminate the program.

Handling errors with an exception allows you the flexibility of letting the application continue running. This provides the programmer a common tool to use to handle errors. Most languages provide it’s own Exception Handling framework. Everything from C to PHP, Java to .NET, they all provide built-in methods to handle exceptions. For my use, all languages provide them except Perl.

How To Do Exception Handling In Perl

Perl5 is probably the most common language that does not provide exception handling. However, like all common programming problems, someone has already thought of the solution. In Perl’s case, you would use the eval() function. Let’s look at our example from above but this time use an Exception Handling method for Perl.

#!/usr/bin/perl -w

use strict;
use DBI;

my $dbh = DBI->connect('DBI:mysql:dbname', 'user', 'pass')
  or die "cannot connect to db";

eval {
  # With the db command, do stuff..
  my $id = connectToWebService('twitter', 'send', '@bob, Hi')
    or die "connectToWebService() failed for twitter...";

  # Insert the $id->{'twitid'}, $id->{'msg'} into the database
  ... run code here ...
  1;
} or do {
  print "error!! - use the $@ variable for info\n";
  ... run more code to handle the error...
  $rc = $dbh->disconnect or warn $dbh->errstr;
}

print "success!\n";

Because the eval block ends with a perl-style return true “1;”, we know that the eval succeeded. If for example an error occurred and connectToWebService didn’t work because it couldn’t connect, eval would not be true and the “or do” block would be run. The die statement in the eval block “throws an exception” and is “caught” by the or do block below.

The “or do” block has access to the $@ global variable. The most common use is to provide a string to the die statemenet thus making it available in the $@ variable. If you are already familiar with exception handling for other languages, exec maps to try while “or do” is the catch code block. The $@ global variable is where you access the error message, if you have thrown one.

This entry was posted in Articles. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>