Tuesday, April 30, 2019

Perl: catch a "die" exception from a subroutine/function


If a subroutine calls die function in Perl, the program will exit.

sub my_fun
{
    die "die in my_fun";
}

my_fun();

print "The end";


The message "The end" won't be printed out in this example.

If we want the program to continue, the trick is to trap the error with an eval block:

sub my_fun
{
    die "die in my_fun";
}

eval {
    my_fun();
};

if ($@) {
    print "Error from my_fun:", $@;
}

print "The end";


The output is:

Error from my_fun:die in my_fun at main.pl line 3.
The end



No comments:

 
Get This <