简体   繁体   中英

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?

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.

What sequence do you expect? Does your code really miss the semicolon after the catch code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM