eval {
# here is put some code that may throw exception
return 1;
} or do {
my $error = $@;
# Handle error.
};
See the Try::Tiny documentation for discussion of the things that can go wrong when using eval
as a try
-type statement, how they can be avoided, and why your posted code ends with 1
(to ensure the eval
block returns a true value if it completes successfully).
After reading it, consider using Try::Tiny instead of going through all the gyrations of making sure each of your eval
s will function correctly as a try
. Laziness is the first great virtue of a programmer, after all.
You could write above eval like,
my $result = eval {
# here is put some code that may throw exception
1; # Why is the "1;" here ?
};
In this case $result
will be 1
only if there was no exception inside eval, and undef otherwise.
So in this particular case 1
ensures that or do {..}
doesn't get executed if there was no exception.
if ($@) {..}
is perhaps more idiomatic way to do the same thing, and $@
is always set when eval{..}
fails.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With