dd-b has asked for the wisdom of the Perl Monks concerning the following question:
I stubbed my toe on the documented behavior of Try::Tiny the other day, and have been working that out. I mostly fixed my code, using the fact that either try or catch block value is returned from the try call (finally block is not). The documentation contains the information -- hidden between the lines and buried deeply at the bottom. Maybe I should take up documentation writing as my next hobby, the "*I* could do better than that" urge is loud.
So then I thought I'd better look at how dies inside the blocks are handled. The documentation doesn't make this clear to me yet.
So, this test program:Produces this output:#! /usr/bin/perl use Try::Tiny; my $res = try { print "point 1\n"; die "point 1.5\n"; 11; } catch { print "point 2\n"; die "point 2.4\n"; 22; } finally { print "point 3\n"; die "point 3.5\n"; 77; }; print "res $res\n";
point 1 point 2 point 2.4 point 3
I expect the die "point 1.5\n" statement to take me out of the try block into the catch block, so that's fine. And it's not surprising I don't hit my final print "res $res\n" statement, one of those dies is going to get me out of there eventually.
But how can I hit print "point 3\n" in the finally block without also hitting die "point 3.5\n"? (And if I put another print after the die in the finally block, it is NOT hit.)
What can I reasonably expect about a die command in the catch block, or the finally block?
Another variation emphasizes the weirdness of dieing in the finally block:
produces#! /usr/bin/perl use Try::Tiny; my $res = try { print "point 1\n"; die "point 1.5\n"; 11; } catch { print "point 2\n"; 22; } finally { print "point 3\n"; die "point 3.5\n"; print "point 3.8\n"; 77; };
point 1 point 2 point 3 res 22
So, my mental model is that the finally block is executed as a subroutine as the next-to-last action before try either returns or re-throws a die out of a catch block, and any die in the finally block is ignored whether or not there was one in the try block. Is this the right model? Can I count on this? The annoying thing about it is that it makes it very hard to use the finally block for cleanup, since lots of modern code counts on using die for error reporting.
I'm running perl 5.10.1 on Centos 6.4, that being the most recent packaged version in the distribution. The point of running "server" distributions is known-compatible packages conservatively chosen, right?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Die inside Try::Tiny blocks
by chromatic (Archbishop) on Apr 26, 2013 at 21:17 UTC | |
by dd-b (Pilgrim) on Apr 27, 2013 at 19:47 UTC | |
by chromatic (Archbishop) on Apr 27, 2013 at 21:50 UTC | |
by dd-b (Pilgrim) on Apr 29, 2013 at 22:10 UTC | |
by chromatic (Archbishop) on Apr 30, 2013 at 00:44 UTC | |
| |
|
Re: Die inside Try::Tiny blocks
by Tommy (Chaplain) on Apr 27, 2013 at 03:29 UTC | |
by dd-b (Pilgrim) on Apr 27, 2013 at 19:43 UTC |