Comment: Re:critic to the rescue (Score 1) on 2009.02.03 0:36
Did you mean to say
if (
eval {
my $obj = SomeClass->new();
die "Code Red!\n";
1;
}
) {
print "No exception occurred\n";
} else {
print "Exception caught: $@\n";
}
Did you mean to say
if (
eval {
my $obj = SomeClass->new();
die "Code Red!\n";
1;
}
) {
print "No exception occurred\n";
} else {
print "Exception caught: $@\n";
}
Following the eval block with an "or" seems to be more reliable than using "if ($@)" to check for an exception in an eval block, because an eval block (or even an eval EXPR) returns undef if there is a syntax error or runtime error or a die statement is executed (according to perldoc -f eval).
eval {
my $obj = SomeClass->new();
die "Code Red!\n";
} or print "Exception caught: $@\n";
But even with this technique the $@ is reset by the destructor in your example, so while the exception at least can be caught we lose the information $@ would provide but for the destructor. The output is merely
"Exception caught:"
The documentation for eval says that $@ is guaranteed to be a null string if no exception occurred; I had not appreciated the precise scope of that statement until seeing your example (it doesn't go on to say that, conversely, $@ is guaranteed not to be a null string if an exception occurred).
I believe I heard schwern advocating at YAPC 2008 the use of
eval {
or warn_about_problem();
rather than
eval {
if ($@) { warn_about_problem() }
This might have been the kind of situation he had in mind.