eval {
dangerous_routine( );
1;
} or do {
error( $q, $@ || "Unknown error" );
};
If dangerous_routine does call
die, then eval will catch
it, set the special variable $@ to the value of
the die message, pass control to the end of the
block, and return undef. This allows us to call
another subroutine to display our error more gracefully. Note that an
eval block will not trap
exit.
This works, but it certainly makes your code a lot more complex, and
if your CGI script interacts with a lot of subroutines that might
die, then you must either place your entire
script within an eval block or include lots of
these blocks throughout your script.
Fortunately, there is a better way. You may already know that it is
possible to create a global signal handler to trap Perl's
die and warn functions.
This involves some rather advanced Perl; you can find specific
information in Programming Perl. Fortunately,
we don't have to worry about the specifics, because there is a
module that not only does this, but is written specifically for CGI
scripts: CGI::Carp.