Error Handling And Exception Catching
Note: This guide is very thin on the ground and only the bare bones. I'll add to it when I get time (whatever that is).
Throwing Exceptions
You can use the die keyword to throw an exception. If it is not caught it causes the whole program to fail and the message you specify is printed to STDERR. E.G.
die "An error occurred.\n";
Catching Exceptions
Catching exceptions is easy using the eval structure:-
eval {
- Code that might thorw an exception here.
}
A die inside there will only propogate up to the level of that eval. You can then discover the error by looking in $!, allowing you to handle the exception without the program crashing. Certain Perl modules will die and if you aren't looking out for the exception you can be taken by surprise.
Another way Of Catching Exceptions
I prefer the following method to catch exceptions when they could be ANYWHERE, and it is a bad idea to use an eval
$SIG{__DIE__} = \&fatalError;
This code tells perl to execute the subroutine fatalError when it receives the DIE signal. This DIE signal is issued when the program terminates abnormally.