J Hall
J Hall

Reputation: 531

Succinct way to change thrown Exception to Failure?

Is there a more succinct way to lift a thrown Exception to a Failure than the following?

try {
    die 'always';
    CATCH { default { fail $_ } }
}

Upvotes: 8

Views: 189

Answers (3)

timotimo
timotimo

Reputation: 4329

Here's a more succinct version of moritz' code.

(try something()) orelse fail $!;

Upvotes: 6

moritz
moritz

Reputation: 12842

try something();
fail $! if $!;

Note that CATCH blocks apply to all statements in the same scope, even to code after the CATCH block. So if you want to use CATCH blocks, be careful about keeping the scope small.

Upvotes: 6

Edwin Buck
Edwin Buck

Reputation: 70909

The try block is superfluous

die 'always';
CATCH { default { fail $_; } }

but I wouldn't worry about saving typed characters. Your intent is clear and highly readable.

Saving typed characters at the cost of expressing your intent or readability might have a place in Perl's legacy, but it's not the place you want to find yourself doing maintenance programming.

Upvotes: 5

Related Questions