How to check exception type in perl?

How can I check which exception caused the completion of a script block or eval? I need to know the type of error and where the exception occurred.

+5
source share
1 answer

Perl Method

Idiomatic Perl is that we either ignore all errors or write them down for logging or forwarding elsewhere:

eval { func() };  # ignore error

or

eval { func() };
if ($@) {
    carp "Inner function failed: $@";
    do_something_with($@);
}

or (using Try :: Tiny - see this page for reasons why you can use it on top of Perl's built-in exception handling):

try { func() }
catch {
     carp "Inner function failed: $_";
     do_something_with($_);
};

If you want to check the type of exception, use regular expressions:

if ( $@ =~ /open file "(.*?)" for reading:/ ) {
    # ...
}

The line and file are also in this line.

, . , CPAN.

Exception:: Class

$@ , . Exception::Class Java. ( ..) , - .

, Error:: Exception,

$SIG{__DIE__} = sub { Exception::Class::Base->throw( error => join '', @_ ); };

Exception:: Class.

Error::Exception Exception:: Class.

+10

All Articles