Skip to content

Commit

Permalink
Show correct way to test eval success
Browse files Browse the repository at this point in the history
* Show correct way to test eval success
* add explanation for not relying on value of $@
  • Loading branch information
Grinnz authored and genio committed Oct 15, 2018
1 parent 7a486a4 commit 22e4db4
Showing 1 changed file with 15 additions and 16 deletions.
31 changes: 15 additions & 16 deletions lib/Exceptions.pm
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,8 @@ die in an C<eval> block. This sounds simple enough, but there are some gotchas
that lead many developers to do this incorrectly.
The correct way to handle an exception requires that you understand how to
preserve the global C<$@> variable. Please see L<Try::Tiny/BACKGROUND> for a
preserve the global C<$@> variable and that its value cannot be relied upon to
determine whether an exception occurred. Please see L<Try::Tiny/BACKGROUND> for a
great explanation of this problem.
Let's look at our previous simple application with error handling using C<eval>.
Expand All @@ -106,32 +107,30 @@ Let's look at our previous simple application with error handling using C<eval>.
# 1
my $value;
my $error = do { # catch block
my $error;
{ # catch block
local $@;
eval { $value = increment(0) }; # try
$@;
};
print "0 plus 1 = ", ($error ? "error": $value), "\n";
$error = $@ || 'Error' unless eval { $value = increment(0); 1 }; # try
}
print "0 plus 1 = ", (defined $error ? "error": $value), "\n";
# error
$value = undef;
$error = undef;
$error = do { # catch block
{ # catch block
local $@;
eval { $value = increment('zero') }; # try
$@;
};
print "zero plus 1 = ", ($error ? "error": $value), "\n";
$error = $@ || 'Error' unless eval { $value = increment('zero'); 1 }; # try
}
print "zero plus 1 = ", (defined $error ? "error": $value), "\n";
# 1
$value = undef;
$error = undef;
$error = do { # catch block
{ # catch block
local $@;
eval { $value = increment(0) }; # try
$@;
};
print "0 plus 1 = ", ($error ? "error": $value), "\n";
$error = $@ || 'Error' unless eval { $value = increment(0); 1 }; # try
}
print "0 plus 1 = ", (defined $error ? "error": $value), "\n";
sub increment {
my $int = shift;
Expand Down

0 comments on commit 22e4db4

Please sign in to comment.