Cloaked eval errors - bug or feature?

  • Thread starter Bas van Sisseren
  • Start date
B

Bas van Sisseren

Hi,

I recently found out i was using a 'local $@' and a 'die' in the same code
block by mistake. The result was an eval error which was cloaked by the
'local $@'. It seems to me this is not the behaviour someone would expect
of this combination.

I'm using perl v5.8.7 from debian sid.

Some examples:
=====[ Example #1 ]=====
#!/usr/bin/perl -w

$@='';

eval {
print "1\n";
eval {
print "2\n";
{
local $@;
die "something";
}
print "3\n";
};
die $@ if $@;
print "4\n";
};

if ($@) {
print "Exception caught: $@";
} else {
print "OK\n";
}
=======[ Result ]=======
1
2
4
OK
========================

The exception isn't caught in the 'die $@ if $@', therefore it isn't
possible anymore to rethrow this exception. It seems like the inner eval
didn't have any problems.

=====[ Example #2 ]=====
#!/usr/bin/perl -w

$@='';

eval {
print "1\n";
eval {
$@="hi there";
print "2\n";
{
local $@;
# die "something";
}
print "3\n";
};
die $@ if $@;
print "4\n";
};

if ($@) {
print "Exception caught: $@";
} else {
print "OK\n";
}
=======[ Result ]=======
1
2
3
4
OK
========================
Normal, expected, behaviour. At the end of the outer eval, the $@ variable
is cleared.

=====[ Example #3 ]=====
#!/usr/bin/perl -w

$@='';

eval {
print "1\n";
eval {
$@="hi there";
print "2\n";
{
local $@;
die "something";
}
print "3\n";
};
die $@ if $@;
print "4\n";
};

if ($@) {
print "Exception caught: $@";
} else {
print "OK\n";
}
=======[ Result ]=======
1
2
Exception caught: hi there at ./eval_test.pl line 16.
========================
Now, the previous $@ is inserted back into the $@ variable. We now have
caught an exception in the outer eval, which was never thrown.


Solution?

I think the $@ should not be set in the code-block of the die itself, but at
the point where code execution resumes, at the end of the eval{} block.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,539
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top