Exception handling in Perl - using eval
Archive - Originally posted on "The Horse's Mouth" - 2010-10-23 08:44:14 - Graham EllisException handling is the trapping of nonstandard results from blocks of code or functions - for example, if I draw a card from a pack and ask you "what suite is this?" you'll usually be able to tell me "it's a heart" or "it's a club" ... but if I had drawn a joker, there would have been no appropriate answer to give and you might have thrown an exception.
Nonstandard results may also be generated where a piece of code fails for some reason - if you try to open a file for reading and the file doesn't exist, or if you perform a piece of arithmetic in which you attempt to divide by zero, for example.
Keywords like try and catch or except, or begin and rescue are provided within many languages (Java, Python, Lua ...) to formalise exception handling, where code which may throw an exception is placed into the first (try or begin) block, and code to be performed if it's trapped is put into the following (catch, except, rescue) block.
Perl doesn't come with any of these keywords (although you can add the syntactic icing via CPAN modules), and by default Perl will exit the program with an error message if your code fails for certain reasons, such as if you divide by zero, or try to set a list member with a position number that's so negative that it's back off the start of a list. However, you can provide the same logic by placing the code from which you want to trap errors into an eval block:
eval {
$n = 30 / $k;
}
If the block fails, it returns a false value - and places the reason for the failure into the special variable $@, so that you can check the return and provide an extra block to handle the 'excpetion' if you wish.
There's a complete example [here]; note the 1; in the end of the eval block which is an excellent general way to ensure that the block will always return a true value if it completes (as is usually the case in Perl, the value returned by a block is the result of the last operation performed in the block).