Search code examples
perlexceptiontry-catchcpanweak-typing

Try::Tiny: Weird behaviour with try-catch or Not?


I am using Try::Tiny for try-catch.

Code goes as below:

use Try::Tiny;

try {
    print "In try";
    wrongsubroutine();  # undefined subroutine
}
catch {
    print "In catch";
}

somefunction();

...

sub somefunction {
    print "somefunction";
}

When I execute It comes like this:

somefunction
In Try
In catch

The output sequence looks wrong to me. Is it wrong? or Is this normal behavior?


Solution

  • Just like forgetting a semi-colon in

    print
    somefunction();
    

    causes the output somefunction to be passed to print instead of $_, a missing semi-colon is causing the output of somefunction to be passed as an argument to catch.

    try {
       ...
    }
    catch {
       ...
    };      <--------- missing
    somefunction();
    

    try and catch are subroutines with the &@ prototype. That means

    try { ... } LIST
    catch { ... } LIST
    

    is the same as

    &try(sub { ... }, LIST)
    &catch(sub { ... }, LIST)
    

    So your code is the same as

    &try(sub { ... }, &catch(sub { ... }, somefunction()));
    

    As you can see, the missing semi-colon after the catch block is causing somefunction to be called before catch (which returns an object that tells try what to do on exception) and try.

    The code should be

    &try(sub { ... }, &catch(sub { ... })); somefunction();
    

    which is achieved by placing a semi-colon after the try-catch call.