I have found that there is the module Error that provides try and catch functionality like in java. But I am confused at how you can print the exception that returns.
I would like to understand how to do the following
try { // do something that will fail! } catch (Error e) { // Print out the exception that occurred System.out.println(e.getMessage()); }
How do I get the print of the error with the stack trace?
Throw, and Try...Catch... The try statement defines a code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
If an exception occurs within the try block, then it is handled by the appropriate exception handler (catch block), associated with the try block. If no exceptions are thrown, then try will return the result of block. A try block should have at least one (or more) catch block(s) or one finally block.
You're probably better off using Try::Tiny which will help you avoid a number of pitfalls with older perl
s.
use Try::Tiny; try { die "foo"; } catch { warn "caught error: $_"; };
Last I checked, Error was deprecated. But here's how you would do it without that module:
eval { die "Oops!"; 1; } or do { my $e = $@; print("Something went wrong: $e\n"); };
Basically, use eval instead of try
, die instead of throw
, and look for the exception in $@
. The true value at the end of the eval block is part of an idiom to prevent $@
from unintentionally changing before it is used again in Perl versions older than 5.14, see P::C::P::ErrorHandling::RequireCheckingReturnValueOfEval for details. For example, this code suffers from this flaw.
# BAD, DO NOT USE WITH PERLS OLDER THAN 5.14 eval { die "Oops!"; }; if (my $e = $@) { print("Something went wrong: $e\n"); } # BAD, DO NOT USE WITH PERLS OLDER THAN 5.14
But note that many Perl operations do not raise exceptions when they fail; they simply return an error code. This behavior can be altered via autodie for builtins and standard modules. If you're using autodie
, then the standard way of doing try/catch is this (straight out of the autodie perldoc):
use feature qw(switch); eval { use autodie; open(my $fh, '<', $some_file); my @records = <$fh>; # Do things with @records... close($fh); }; given ($@) { when (undef) { say "No error"; } when ('open') { say "Error from open"; } when (':io') { say "Non-open, IO error."; } when (':all') { say "All other autodie errors." } default { say "Not an autodie error at all." } }
For getting a stacktrace, look at Carp.
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