Hack #91. Write Less Error-Checking Code
Identify runtime errors without writing code.
One of the less-endearing features of working with the outside world is that things can fail: you might run out of disk space, lose your network connection, or have some other sort of serious error. Robust programs check for these errors and retry or fail gracefully as necessary. Of course, checking every potential point of failure for every possible failure can make a lot of repetitive code.
Fortunately, Perl provides a way to fail on errors without having to check for them explicitly—the Fatal core module.
The Hack
One of the most failure-prone points of programming is IO programming, whether working with files or other computers across a network. File paths may be wrong, file permissions may change, disks can mysteriously fill up, and transitory networking problems may make remote computers temporarily invisible. If you work much with files, using Fatal can reduce the amount of code you need to write.
The
Fatal module takes a list of function names to override to raise exceptions on failures. open and close are good candidates. Pass their names to the use line to avoid writing the or die( ) idiom:
use Fatal qw( open close );
open( my $fh, '>', '/invalid_directory/invalid_file' );
print {$fh} "Hello\\n";
close $fh;If you run this (and don't have a directory named /invalid_directory), you'll receive an error message:
Can't open(GLOB(0x10159d74), >, /nodirectory/nofile.txt): No such file or directory ...