Reputation: 972
I have a try catch block in perl
try {
//statement 1
//statement 2
};
catch Error with
{
print "Error\n";
}
When I run the perl program I get the following error
Can't Call method "try" without a package or object reference at...
Upvotes: 4
Views: 4265
Reputation: 1083
You might also want to give Nice::Try a try. It is quite unique and provides all the features of a trycatch block like in other programming languages.
It supports exception variable assignment, exception class, clean-up with finally
block, embedded try-catch blocks.
Full disclosure: I have developed Nice::Try when TryCatch got broken.
Upvotes: 0
Reputation: 8542
You probably wanted one of the CPAN modules such as Try::Tiny
:
use Try::Tiny;
try {
# statement 1
# statement 2
}
catch {
print "Error\n";
};
Upvotes: 5
Reputation: 204956
Perl does not provide try
or catch
keywords. To trap "exceptions" thrown by die
, you can set a $SIG{__DIE__}
handler or use eval
. Block form is preferred over string form, as parsing happens once at compile time.
eval {
// statement 1
// statement 2
}
if ($@) {
warn "caught error: $@";
}
There are various modules that provide more traditional try
-like functionality, such as Try::Tiny
.
Upvotes: 6