ext_142433 ([identity profile] winterkoninkje.livejournal.com) wrote in [personal profile] winterkoninkje 2006-07-17 08:40 pm (UTC)

Sort of. (That's C++ and Java, btw. C lacks it.) The way try-catch works is similar to interrupt handling (don't know if you've dealt with that either); basically a function can opt to "throw an exception" (i.e. error) instead of returning normally, and then if the call to that function is wrapped in a try block the exception will be handed off to an exception handler. Sic:


sub foo($x) throws omg { if ($x) { return true; } else { throw new omg(); } }
sub bar($y) { try { foo($y) ; } catch (omg) { die "omg!"; } }


If you didn't have the try-catch then the call to foo() is equivalent to throwing the exception out of bar() and so you'll keep unwinding the stack until you find some enclosing try-catch environment. IIRC, it's done more efficiently at the assembly level, but that's what the semantics are.

You can have multiple catch blocks per try block for catching different types of exceptions, and in Java you need to declare what sorts of exceptions can be thrown. In Perl there's no throw-try-catch because the exec() function serves the same general need in a somewhat different fashion, though `man perlsub` discusses that more.

Exceptional flow of control can be useful, but that's not quite what I'm going for here. Exceptions are expensive (though not as expensive as interrupts since there's no trapping into the kernel) and so should only be used when they're needed (though Java ignores this and uses them everywhere, e.g. in lieu of returning null pointers).

The sanity checking is more for convenience of cleaning up code and making it legible, though I suppose one could look at it as an exception on the expression level (instead of the function level) which is automatically caught (and generally discarded). In some ways it's similar to Perl's `||` operator when used for things like: $x ||= $default; as a shorthand for $x = $x ? $x : $default;, insofar as it reduces redundancy from doing things like $x != null && $x->foo();

Post a comment in response:

This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

If you are unable to use this captcha for any reason, please contact us by email at support@dreamwidth.org