Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - messing try/catch with eval

How to catch exception from inner eval {}?

#!/usr/bin/perl
use strict;
use warnings;

use Try::Tiny;
use Exception::Class ('T');

use Data::Dumper;

try {
    eval {
        T->throw("Oops");
    };
    } catch {
        print Dumper \$_;
    };
}

We have got not Exception::Class submodule, but scalar instead. More precisely, I have a lot of legacy code with require, and require seems to use eval inside.

like image 680
Eldhenn Avatar asked Nov 22 '25 21:11

Eldhenn


2 Answers

You can automatically upconvert exceptions as follows:

#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say );

use Try::Tiny;
use Exception::Class ('T');

$SIG{__DIE__} = sub {
   die($_[0]) if !defined($^S);
   die($_[0]) if ref($_[0]) eq 'T';
   T->throw($_[0]);
};

try {
    die "foo";
} catch {
    say ref($_) || "Not reference";
    print $_;
};

try {
    T->throw("foo");
} catch {
    say ref($_) || "Not reference";
    say $_;
};
like image 108
ikegami Avatar answered Nov 25 '25 11:11

ikegami


If an exception is encountered inside an eval block, the return value of the block is undef (or an empty list in list context) and Perl sets the special variable $@ with the error message. The error message is usually a simple scalar but it can be a reference or blessed reference -- one way that it gets set is with the argument to a die call, and any type of value may be passed to that function.

try {
    eval {
        T->throw("Oops"); 1;
    } or do {
        warn "Exception caught in eval: $@";
        # rethrow the exception outside eval
        if (ref($@) eq 'T') {
            $@->rethrow;
        } else {
            T->throw("Oops: $@");
        }
    }
} catch {
    print Dumper \$_;
};
like image 30
mob Avatar answered Nov 25 '25 09:11

mob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!