Exception Handling (when to use it)

Andy Armstrong andy at hexten.net
Fri Jul 13 12:34:39 BST 2007


Ovid wrote:
> ----- Original Message ----
> From: Andy Armstrong <andy at hexten.net>
> 
>> I've seen the 'hack' of looping over a string or array and relying on
>> the ArrayIndexOutOfBounds (or whatever it's called) exception to break
>> out of the loop in more than one Java program.
> 
> Wow.  That really confuses me.  The person who explained to my why Java exceptions should only be used with a true exception was none other than James Duncan Davidson (you know, the guy who created Tomcat, Ant, and the Java XML API spec).  Apparently, when an exception in Java is thrown, most VMs have to do a huge amount of work collecting and serializing data and making it available in an Exception object.  If the exception is caught and the program resumes, it then has to do a lot of work with this data to ensure that the VM is in an appropriate state to resume where it left off. (Any conceptual errors here are mine, not his).

I think the case that started the madness was some code from Sun that
processes big buffers. I guess they'd benchmarked it and found that the
overhead of throwing an exception to break out of the loop was smaller
than the overhead of testing the loop index each time. Or maybe not.
Maybe someone at /Sun/ just thought it was cute.

It's certainly hideous if you haven't benchmarked - and probably even if
you have.

I used to have commit on Tomcat. Might still do. I should go in and
'fix' a few of the loops :)

> Does Perl have similar limitations?  I've never worried about it that much, to be honest.

Well it's a lot less of a worry if you're using exceptions as intended :)

-- 
Andy Armstrong, Hexten


More information about the london.pm mailing list