Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 43 ยท Modules and Errors

Errors, die and eval

Handle errors in Perl with die and warn, trap them with eval, avoid the $@ pitfalls, throw exception objects, and use Try::Tiny, try/catch and Carp.

Programs fail: a file is missing, a network call times out, a user types nonsense. Perl has no throw keyword. It has a smaller set of tools that work together: die raises an error, eval catches one, warn reports a problem without stopping, and the special variable $@ holds the last error. On top of those, modern Perl adds a try/catch feature and CPAN has Try::Tiny.

This lesson shows how to raise and trap errors, the traps to avoid, how to throw rich exception objects, and how Carp makes error messages point at the right line.

Perl is not installed on this site, so the Perl code is read-only and every output shown was captured from a real run. The interactive examples are Python stand-ins showing the same flow (raise, catch, clean up).

die and warn

die prints its message to standard error and ends the program with a non-zero exit code. warn prints the message but keeps going.

PERL
use v5.36;

warn "disk is almost full\n";
die "cannot continue\n" if 1;
say "never printed";

There is an important detail about the final newline. If the message ends with \n, Perl prints it as it is. If it does not, Perl appends " at SCRIPT line N." so you can find the spot.

PERL
die "boom\n";      # boom
die "boom";        # boom at script.pl line 3.

Use a newline for errors aimed at users of your program ("file not found") and leave it off for programmer errors where the location helps.

The usual place for die is after an operation that can fail. The $! variable holds the operating system's reason:

PERL
open(my $fh, '<', 'data.txt') or die "Cannot open data.txt: $!\n";

You met this pattern in the file I/O lesson. If you have not read it yet, see Reading and Writing Files.

Trapping errors with eval

An eval block runs code and catches any die inside it. If the code dies, the block stops, eval returns undef, and the message lands in $@. If the code succeeds, $@ is set to an empty string.

PERL
use v5.36;

eval { die "boom\n" };
print "caught: $@";                 # caught: boom

my $result = eval { 10 / 0 };
print "error: $@";                  # error: Illegal division by zero at script.pl line 6.
say defined $result ? 'value' : 'undef';   # undef

eval { 1 };
say "after success: [", $@, "]";    # after success: []

The eval/die cycle

eval { } Runs a block and protects the program.
die Stops the block with a message or object.
$@ Holds the error, or an empty string.
1 / 2

The reliable eval pattern

A block that returns a false value (for example 0) can fool a check on its return. Make the last statement 1; and test the return value of eval:

PERL
my $ok = eval {
    risky_operation();
    1;
};
if (!$ok) {
    my $error = $@ || 'unknown error';
    warn "operation failed: $error";
}

Copy $@ into a variable right away, because the next eval anywhere (even one inside another module) resets it.

Here is the same shape in Python, with try, except and finally:

Python Stand-in: raise, catch, clean up

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Perl the "finally" part is usually done with try/catch (below) or by making cleanup happen automatically through lexical variables and DESTROY.

Pitfalls with $@

  • It is global. Any later eval clears it. Save it first: my $err = $@;.
  • A false-looking error. An exception object can be false if its class overloads boolean conversion, so if ($@) may miss it. Check the return value of eval rather than only $@.
  • Old cleanup bug. In Perl before 5.14, an object whose DESTROY method used eval could wipe the error that was in flight. Modern Perl fixes this, but code that must support very old Perls often saves $@ carefully, which is one reason Try::Tiny exists.
  • Nested evals. An inner eval that fails and is handled leaves its message in $@. If you then die without a new message you get a confusing combined text.
  • Rethrowing. To pass an error to the caller, die $err with the saved value. Plain die with no arguments reuses $@ and adds "\t...propagated".
PERL
eval {
    eval { die "inner\n" };
    print "inner: $@";        # inner: inner
    die "outer\n";
};
print "outer: $@";            # outer: outer

Exception objects

A string is fine for simple scripts. Larger programs throw objects so a handler can ask what kind of error occurred and read details instead of matching text. die accepts any value, including a blessed reference.

PERL
use v5.36;

package MyError {
    sub new   ($class, %args) { return bless { %args }, $class }
    sub throw ($class, %args) { die $class->new(%args) }
    sub message ($self) { return $self->{message} }
    sub code    ($self) { return $self->{code} }
}

eval { MyError->throw(message => 'disk full', code => 28) };

if (my $e = $@) {
    if (ref $e && $e->isa('MyError')) {
        say "known error: ", $e->message, " (", $e->code, ")";
    }
    else {
        die $e;          # not ours: pass it on
    }
}
TEXT
known error: disk full (28)

Test with ref($e) && $e->isa('Class') (or blessed from Scalar::Util) so a plain string error does not make the method call crash. Modules on CPAN such as Throwable and Exception::Class build on this idea, and you will understand bless and isa fully after Classes and Objects and Inheritance, Roles and Moo.

Python Stand-in: custom exception classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The try/catch feature

Perl 5.34 added real try/catch syntax, and since 5.40 try/catch is a stable feature (the finally block is still marked experimental). It is easier to read than eval, and return inside a try block returns from the enclosing subroutine as you would expect.

PERL
use v5.40;
use feature 'try';

sub parse_age ($text) {
    try {
        die "not a number\n" if $text !~ /\A\d+\z/;
        return $text + 0;
    }
    catch ($e) {
        chomp $e;
        return "invalid ($e)";
    }
}

say parse_age('42');      # 42
say parse_age('abc');     # invalid (not a number)

The error arrives in the lexical variable $e, so $@ problems do not apply. On older Perls this syntax is not available, and you need eval or a module.

Try::Tiny

Try::Tiny from CPAN is the long-standing answer for older Perls and gives a friendly try, catch and finally that handle $@ correctly. Inside catch the error is in $_.

PERL
use Try::Tiny;

my $value = try {
    die "bad input\n";
    1;
}
catch {
    chomp;
    "caught [$_]";
}
finally {
    say "cleanup";
};

say $value;
TEXT
cleanup
caught [bad input]

One gotcha: the blocks are anonymous subroutines, so return inside them returns from the block, not from your function. The built-in try/catch feature does not have this surprise.

Reporting errors with Carp

When a module function is called wrongly, the useful line number is the caller's, not the line inside the module. The core module Carp provides this.

PERL
package Account;
use Carp qw(croak carp confess);

sub withdraw ($self, $amount) {
    croak "Insufficient funds" if $amount > $self->{balance};
    $self->{balance} -= $amount;
}

When user code calls $account->withdraw(50) on line 5 of the script, the error reads Insufficient funds at script.pl line 5., which points at the faulty call.

  • croak is die from the caller's point of view.
  • carp is the matching warn.
  • confess and cluck add a full stack trace to the error or warning, useful while debugging.

Practical advice

  • Use or die after every system call that can fail (open, close, mkdir, rename).
  • Put the reason in the message: include file names and values.
  • Catch errors only where you can do something about them. Otherwise let them propagate.
  • Throw objects in libraries and strings in short scripts.
  • Never swallow errors silently with an empty handler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between die "oops" and die "oops\n"?

    Without a trailing newline, Perl adds 'at FILE line N.' to the message. With a newline the message is used unchanged.
  2. 2. After eval { 1 }; succeeds, what does $@ contain?

    A successful eval resets $@ to an empty string, which is why a fresh error shows up as a non-empty value.
  3. 3. Why should you copy $@ to a variable soon after an eval?

    $@ is a package variable. Any later eval, even in another module, can reset it.
  4. 4. Which tool should you use to make croak report the caller's line instead of the library's line?

    Carp's croak and carp report errors from the point of view of the code that called the function.
  5. 5. Which test is the safest way to check whether a caught error is an object of class MyError?

    Checking ref first avoids calling a method on a plain string, and isa also accepts subclasses.

Summary

  • die raises an error and warn reports one; a trailing \n suppresses the "at ... line N" addition.
  • eval { ... } traps errors; the message is in $@, which is empty on success.
  • Use the eval { ...; 1 } pattern, copy $@ immediately, and beware of nested evals.
  • Throw blessed objects for rich, testable exceptions and check them with ref and isa.
  • try/catch is built into modern Perl (stable in 5.40); Try::Tiny covers older versions, with its own return behavior.
  • Carp (croak, carp, confess) puts the blame on the caller.

Next, create your own types with Classes and Objects.