The Right Approach to Exceptions

Ben Davis entheh at
Sat Feb 18 17:43:27 PST 2012

On 19/02/2012 00:48, Jonathan M Davis wrote:
> On Saturday, February 18, 2012 16:46:43 H. S. Teoh wrote:
>> I can't believe something this simple has to be explained so
>> elaborately. I thought all of us here knew how to use OO??
> I think that the problem stems from people frequently using exceptions
> incorrectly, and many of the C++ programmers probably haven't _ever_ seen them
> used correctly, since I don't think that it's very common for C++ programs to
> define exception hierarchies - especially not advanced ones like Java has. And
> when you see a lot of bad exception code, that tends to turn you off to them,
> and it definitely doesn't show you how to use them correctly.
> - Jonathan M Davis

I can assure you they get misused in Java too. Most people write this:

try {
    lots and lots and lots of stuff here
catch (Exception e) {}

All they wanted to do was get round the compile error because they 
called Thread.sleep() which throws InterruptedException which you're 
required to catch, and they know they're never going to call 

What they end up doing is catching NullPointerException, 
ArrayIndexOutOfBoundsException and all the other things that really 
matter, and nasty bugs can go undiagnosed.

Eclipse's auto-fix impoves things a little - it can generate this for you:

try {
catch (InterruptedException e) {	//For example
	//TODO: auto-generated catch block

But no one does their TODOs, and no one takes care to keep the console 
output short enough to be useful.

You CAN write "throw new RuntimeException(e)", and you won't be required 
to catch that one. And then exceptions are incredibly useful, and I've 
even found rare cases where creating my own checked exception makes an 
API much safer. (I was processing code, and I had something like an 
'uninline' operation that occasionally couldn't work, so the caller had 
to always have a backup plan in case the exception was thrown.)

So it could be a good system, but no one has any idea what they're doing 
with it.

If I had to improve the Java one, I suppose I would:

- distinguish between 'bug' exceptions (e.g. null) and 'you're more 
likely to want to catch this' exceptions (e.g. IO). Maybe the bug ones 
should have been Errors, since people *usually* don't catch those (and 
are certainly never required to). As it stands, Errors are reserved for 
corrupt class files and other VM panic scenarios.

- make sure the 'lazy' approach is a good one: the less you type, the 
fewer exceptions you catch, and the less likely you are to silence those 
exceptions at runtime. Probably the main problem with the exception 
hierarchy is that the short names tend to be the more general ones that 
are more dangerous to catch indiscriminately.

More information about the Digitalmars-d mailing list