Sunday, August 5, 2012

Basic Error Handling in Perl


Anyone that has ever sat at a computer help desk quickly becomes aware of just how many issues a user can have with even the seemingly easiest and most user friendly software around.  Whether it is the user that “lost” his email because he clicked on one of the sort buttons and now can’t find today’s messages or the user who manages to crash a calculator-like program because he decides to type “two” instead of “2”, it becomes readily apparent that computer users will often do things that many developers would find unthinkable.  It is important that software developers learn this lesson early in their career.  Whether for malicious reasons or innocuous ones, your application will be abused by those that make use of it.  While some previous posts discussed the basics of input validation and some modules that could be used to perform input validation, these are not the only useful techniques to consider.   Error handling is also a useful technique for dealing with potentially problematic situations that could arise.  For example, perhaps your application requires access to a file on removable media for certain functions or connection to a certain network resource.  While an “or die” type statement alone could be used to deal with the situation, error handling may provide you with a way to allow your application to route around the error or to at least fail gracefully.  The basics of Perl error handling is the eval statement, which is used as follows:

#!usr/bin/perl

use strict;
use warnings;

my $x=5;
my $y=0;

eval {
    my $result=$x/$y;
    print "$result";
    1;
} or do {
    print "Error: $@\n";
};

The above code works because if the code in the eval block executes it will return true, otherwise it will return false, and cause the code contained in the do block to execute.  The above example, forces the do block to execute by intentionally dividing by zero. 

It is also notable that there are several Perl modules that are highly useful for error handling as well such as Exception::Class, Error, and TryCatch.  These modules will be looked at in more detail in a future installment.  

No comments: