TExcelTAD
Home › Perl › Error Handling

Error Handling

Things go wrong: files are missing, input is malformed, numbers are zero. Perl's basic error mechanism is simple: die throws an exception, and eval (or the modern try/catch) catches it.

die and warn

die LIST stops the program with a message on standard error (exit status 255 when uncaught). warn LIST prints a message but carries on. If the message does not end with a newline, Perl appends the script name and line number:

perl · try it yourself
use strict;
use warnings;

warn "Low disk space\n";
warn "Config value missing";
print "Still running\n";
die "Cannot continue\n";
print "This line never runs\n";
Still running
Low disk space
Config value missing at /app/output.s line 5.
Cannot continue

(As before, the runner shows standard error after standard output.) End messages for users with \n; leave it off while debugging so you can see where the error happened.

Catching errors with eval

eval BLOCK runs code and catches any die inside it. If an error occurred, eval returns undef (or an empty list) and the error is stored in $@; on success $@ is the empty string:

perl · try it yourself
use strict;
use warnings;

sub divide {
    my ($a_num, $b_num) = @_;
    die "Division by zero\n" if $b_num == 0;
    return $a_num / $b_num;
}

for my $pair ([10, 4], [3, 0]) {
    my $result = eval { divide(@$pair) };
    if (defined $result) {
        print "@$pair -> $result\n";
    } else {
        print "@$pair -> failed: $@";
    }
}
print "Program continues\n";
10 4 -> 2.5
3 0 -> failed: Division by zero
Program continues

The safe eval idiom

$@ can be clobbered by code that runs while the error propagates (for example a DESTROY method that uses eval). The robust idiom makes the eval block return true on success and tests that:

perl · try it yourself
use strict;
use warnings;

sub parse_age {
    my ($text) = @_;
    die "Not a number: '$text'\n" unless $text =~ /^\d+$/;
    die "Unrealistic age: $text\n" if $text > 150;
    return $text + 0;
}

for my $input ("42", "abc", "200") {
    my $age;
    my $ok = eval {
        $age = parse_age($input);
        1;                      # reached only if nothing died
    };
    if ($ok) {
        print "Age is $age\n";
    } else {
        my $err = $@ || "unknown error";
        print "Error: $err";
    }
}
Age is 42
Error: Not a number: 'abc'
Error: Unrealistic age: 200

try / catch / finally

Since Perl 5.40, the try feature is stable. It avoids the $@ pitfalls and reads like other languages; the error arrives in a lexical variable:

perl · try it yourself
use strict;
use warnings;
use feature 'try';
no warnings 'experimental::try';   # only finally{} is still experimental

sub load_config {
    my ($name) = @_;
    die "Unknown config '$name'\n" unless $name eq "prod";
    return { db => "db.prod.local" };
}

for my $env ("prod", "staging") {
    try {
        my $cfg = load_config($env);
        print "$env uses $cfg->{db}\n";
    }
    catch ($e) {
        print "Failed: $e";
    }
    finally {
        print "-- finished $env\n";
    }
}
prod uses db.prod.local
-- finished prod
Failed: Unknown config 'staging'
-- finished staging

finally always runs, whether or not an error happened. try/catch alone is stable since 5.40, but adding a finally block still triggers an "experimental" warning in Perl 5.42, which the no warnings line switches off.

Exception objects

die can throw any scalar, including an object. That lets callers inspect the kind of error instead of parsing strings:

perl · try it yourself
use strict;
use warnings;
use feature 'try';
use Scalar::Util qw(blessed);

package NotFound {
    sub new    { my ($c, %a) = @_; bless {%a}, $c }
    sub throw  { my $c = shift; die $c->new(@_) }
    sub message { "No such item: $_[0]{item}" }
}

my %stock = (apple => 3);

sub take {
    my ($item) = @_;
    NotFound->throw(item => $item) unless exists $stock{$item};
    die "Out of stock: $item\n" if $stock{$item} == 0;
    return --$stock{$item};
}

for my $item (qw(apple kiwi)) {
    try {
        my $left = take($item);
        print "Took one $item, $left left\n";
    }
    catch ($e) {
        if (blessed $e && $e->isa('NotFound')) {
            print "Handled: ", $e->message, "\n";
        } else {
            die $e;              # rethrow errors we don't handle
        }
    }
}
Took one apple, 2 left
Handled: No such item: kiwi

System errors: $!

When a system call such as open fails, it returns false and puts the reason in $!. Include it in your message:

perl
open(my $fh, '<', 'missing.txt') or die "Cannot open missing.txt: $!\n";
# Cannot open missing.txt: No such file or directory

The core module autodie (use autodie;) makes open, close and friends die automatically with a descriptive message, so you can drop the or die checks.

Test yourself

Where does eval { ... } store the error message?

  1. $!
  2. $@
  3. $_
  4. $0

What happens when a die message does not end in \n?

  1. Nothing different
  2. Perl appends at SCRIPT line N.
  3. The program does not stop
  4. The message is hidden

Why write my $ok = eval { ...; 1 }; and test $ok?

  1. It is faster
  2. Because $@ can be clobbered, while the return value of eval is reliable
  3. To return 1 from the program
  4. It is required syntax