Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices for error handling in Perl?

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?

like image 810
Mike Avatar asked May 19 '10 20:05

Mike


2 Answers

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.

like image 143
friedo Avatar answered Sep 28 '22 08:09

friedo


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).

like image 34
codeholic Avatar answered Sep 28 '22 08:09

codeholic