The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at
Sat Feb 18 17:54:46 PST 2012

On Sunday, February 19, 2012 01:43:27 Ben Davis wrote:
> I can assure you they get misused in Java too. Most people write this:

Oh yes. It's not like the fact that their exception hierarchy is good means 
that people don't misuse it. Far too many people try and ignore errors in any 
language. And a solid exception hierarchy does nothing to stop people from 
being stupid and simply catching Exception to ignore. But if you have a good 
exception hierarchy, then you _can_ properly handle errors if you want to.

My point was that because C++ doesn't have a standard exception hierarchy 
(even worse, they let you throw literally anything), it's much rarer to see 
one in C++ programs, let alone a good one. So, it's something that many C++ 
programmers have not been exposed to. Java programmers do not have that 
excuse. So, it's arguably that much worse when they misuse exceptions.

> - 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.

Well, in D, you'd use exceptions derived from Error (though null pointers 
still result in a good ol' segfault). Java's situation is marred by the whole 
thing with checked exceptions. D's basic is better in that regard, I think. 
It's the lack of a proper exception hierarchy where we're worse.

> - 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.

You mean, make the standard exception names really long and ugly, and the more 
specific ones short? e.g. Exception becomes something like 
StandardExceptionThatYouReallyShouldBeCatchingCatchTheDerivedType whereas 
specific exceptions are more like SpecifcEx (though that's a bit extreme)?

Well, while that's a good sentiment, the very nature of more specific 
exceptions means that their namesj are likely to be more specific and therefore 
longer (especially when you have descriptive names). So, I'm not sure that 
that's ultimately all that reasonable, even if the basic idea is a good one.

- Jonathan M Davis

More information about the Digitalmars-d mailing list