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?
Whether die
is appropriate in the middle of the script really depends on what you're doing. If it's only tens of lines, then it's fine. A small tool with a couple hundred lines, then consider confess (see below). If it's a large object-oriented system with lots of classes and interconnected code, then maybe an exception object would be better.
confess in the Carp package:
Often the bug that led to the die isn't on the line that die reports.
Replacing die with confess (see Carp package) will give the stack trace (how we got to this line) which greatly aids in debugging.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With