igni
igni

Reputation: 134

In Perl, an error occurred inside the inner eval{} can also be caught by the outer eval{}?

not so clear about this feature.

the situation is we have API which has its own eval catch, it returns normally a status. we use this API and need a specific status about the execution, the idea is to do an outer eval to catch if any error raised by the API. is it possible ? or it's ignored by the inside eval.

Upvotes: 0

Views: 1015

Answers (2)

Pradeep
Pradeep

Reputation: 3153

Will work, checkout this example...

use strict;
use warnings;

eval { api_function(); };

if ($@) {
    warn "Oops! API error!";
}

sub api_function {

    eval {
        my $a = 1;

        my $x = 1 / $a;
    };

    if ($@) {
        warn "Oops! error!";
    }

    my $a = 0;

    my $x = 1 / $a;
}

Upvotes: 0

e.dan
e.dan

Reputation: 7475

If the API "throws" an error with die when it "catches" an error, then yes, your outer eval can "catch" it and handle it as it wants. If the API catches and just returns an error code as, say, a return value, then you don't need an outer eval. A more specific example might help...

Upvotes: 2

Related Questions