There are two ways to deal with this. One is mentioned above, and that is wrapping dying code in eval{}, which is sort of like Java's try setup. Code inside the eval block may die, but if it does, it merely ends the eval block (and, as a bonus, $@ gets set to the message it died with).
eval {
... code that might die ...
};
if ($@) {
# if we had an error.
... read $@ and decide on what to do ...
}
However, if you will always do the same thing upon death, you can also override the "die" signal. This would be used, for example, if you want to return a useful exit code to a wrapper script.
$SIG{__DIE__} = \&my_death;
sub my_death {
warn @_; #propagate the message via warn()
POSIX::_exit(42); #exit with code 42
}
You should read about this in the perldocs before going the route above, as certain things (like I/O) are not a good idea when your app is in the throes of death. ;-)
Update: I forgot to add, if you do want to do "dangerous" things to recover from a fatal error, one way to accomplish this is to wrap your script's main logic in a subroutine (say, main()), and do something like this:
sub main {
... main program logic ...
}
eval { main() };
if ($@) {
... handle any fatal errors ...
}
This allows you to, among other things, put common housekeeping-on-exit routines inside an END{} block. For example:
eval { main() };
if ($@) {
warn "FATAL: $@"; ## all I want to do is warn about the fatal.
}
END {
close_all_files();
issue_done_to_server();
}
This way, you will close all files and issue a done to the server (I made those up, BTW) whether you had fatal errors or not.
Larry Wall is Yoda: there is no try{}
The Code that can be seen is not the true Code
|