Search code examples
perlerror-handlingtry-catch

How to properly use the try catch in perl that error.pm provides?


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?


Solution

  • You're probably better off using Try::Tiny which will help you avoid a number of pitfalls with older perls.

    use Try::Tiny;
    
    try {
            die "foo";
    } catch {
            warn "caught error: $_";
    };