What are the best practices for error handling in Perl?
error-handling, perl
Solution
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.
Problem
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?