prashanthkvs
prashanthkvs

Reputation: 263

Exception Handling in perl

I have seen a 1 appear at the end of eval blocks for exception handling in perl. Why is that required? What happens if an eval block returns false?

Is this required even if we dont use $@ directly but some library from CPAN to do exception handling?

Upvotes: 4

Views: 732

Answers (2)

rjh
rjh

Reputation: 50274

To expand on ikegami's answer: most people write code like this:

eval { might_throw_exception() };
if ($@) { ... }

This is wrong pre-5.14, because $@ may not be a true value even if an exception was thrown due to a destructor overwriting it, or other factors. return 1 is a workaround; see Try::Tiny for a full explanation.

Upvotes: 0

ikegami
ikegami

Reputation: 385496

What happens if an eval block returns false?

That false value is returned by eval.

Why is that required?

It's not required.

my $foo = eval { foo() };

is perfectly fine if you're ok with $foo being undef on exception.

What you've seen is

if (!eval { foo(); 1 }) {
   ...
}

The code is returning true to let the if know the eval succeeded. eval will return false on exception.

Upvotes: 6

Related Questions