I'm learning Perl, and in a lot of the examples I see errors are handled like this
open FILE, "file.txt" or die $!;
Is die
in the middle of a script really the best way to deal with an error?
I'm learning Perl, and in a lot of the examples I see errors are handled like this
open FILE, "file.txt" or die $!;
Is die
in the middle of a script really the best way to deal with an error?
The more modern approach is to use the Carp standard library.
use Carp;
my $fh;
open $fh, '<', "file.txt" or confess($!);
The main advantage is it gives a stack trace on death.
I use die but I wrap it in eval blocks for control over the error handling:
my $status = eval
{
# Some code...
};
If the 'eval' fails:
$status
will be undefined.$@
will be set to whatever error message was produced (or the contents of
a die
)If the 'eval' succeeds:
$status
will be the last returned value of the block.$@
will be set to ''.Whether die
is appropriate in the middle of the script really depends on what you're doing. If it's a small tool with a couple hundred lines, then it's probably fine. If it's a large object-oriented system with lots of classes and interconnected code, then maybe an exception object would be better.
For handling exceptions from Perl builtins, I like to use autodie. It catches failures from open
and other system calls and will throw exceptions for you, without having to do the or die
bit. These exceptions can be caught with a eval { }
, or better yet, by using Try::Tiny.
Since I use Log::Log4perl almost everywhere, I use $logger->logdie
instead of die
. And if you want to have more control over your exceptions, consider Exception::Class.
It is better to catch your exceptions with Try::Tiny (see its documentation why).