I'm generating a Perl code from Java code and try to simulate the try
catch
mechanism.
I cannot use external libraries. I found two possible methods to simulate this behavior:
First one:
eval {
...
};
if ($@) {
errorHandler($@);
}
Second:
unless(.....){
// handle the error
}
My knowledge in Perl is very little. As I understand, the first solution enables me to execute multiple commands while the second solution enables me to execute only 1 command. But, I also saw that using eval is not recommended.
What is the "right" way of doing it?
your second snippet doesn't catch exceptions at all, so it's not an option. Your options in core[1] are:
my $rv;
if (!eval { $rv = f(); 1 } ) {
warn($@);
}
my $rv = eval { f() };
if ($@) {
warn($@);
}
Downside (of this second version): Before 5.14, an exception can go unnoticed if an object destructor clobbers $@
.
Outside of core,
use TryCatch;
try {
f();
} catch($e) {
warn($e);
}
use Nice::Try;
try {
f();
} catch($e) {
warn($e);
}
use Try::Tiny;
my $rv = try {
f();
} catch {
warn($_);
};
Downside (of the Try::Tiny version): The blocks are subs in disguise, so you can't use return
from within them.
There may be others.