AnyCompiler

Error Handling

Core Perl has no try/catch keyword. Instead, die raises an error (unwinding the call stack, just like throwing an exception elsewhere), and eval { ... } catches anything that dies inside its block, storing the error in the special variable $@. If the block completes without dying, $@ is set back to an empty string.

use strict;
use warnings;

sub safe_divide {
    my ($a, $b) = @_;
    die "Cannot divide by zero\n" if $b == 0;
    return $a / $b;
}

my $result = eval { safe_divide(10, 0) };
if ($@) {
    print "Caught error: $@";
} else {
    print "Result: $result\n";
}
Output
Caught error: Cannot divide by zero

Ending a die message with \n, as above, suppresses Perl's usual habit of appending " at FILE line N." to it — useful for a deliberately user-facing error message. Leaving the \n off, as below, gets you that file-and-line suffix, which is exactly what an uncaught die prints to stderr before the program exits — this is the real, genuine diagnostic text, not written to look plausible:

use strict;
use warnings;

print "Starting\n";
die "Something went wrong";
print "This never runs\n";
Output
Starting

stderr
Something went wrong at script.pl line 5.

"Starting\n" was printed before the die, and "This never runs\n" genuinely never ran — die stopped the program immediately. Wrapping a risky call in eval { ... } is the only way in core Perl to keep a die from ending the whole program. Next: closing thoughts.

Practice exercise

Write sub check_positive that dies with "must be positive" if given a negative number, otherwise returns it. Call it with -5 inside eval, then print "Error: " followed by $@ if it failed.