This tutorial explains how to handle errors and exceptions in Perl Language.

Before Perl version 5.34, to handle exceptions, Third-party libraries such as Try::Tiny were used. Here is an example before

use Try::Tiny;

try {
        die "foo";
} catch {
        warn "error thrown: $_";
};

Perl version 5.34 introduced try,catch, and finally syntax features

These are experimental features, enabled by using the below command.

use feature 'try'

Syntax:

try {
    // code
}
catch ($e) {
    warn "catch block; $e";
}
finally {
    print "finally block\n";
}

finally block is an optional.

if finally included, It executes the code inside it after the code is executed to try and catch blocks.

Notes:

  • The finally block does not allow to use of return, goto, or loop controls.