mardi, avril 24, 2007

Exceptions, the Widest net effect and a new Exception catching syntax

One annoying thing with Exceptions Catching in java is obviously the fact that a lot of APIs still throw checked Exceptions (not inheriting from java.lang.RuntimeException) to your face, therefore forcing you to deal systematically with things that sometimes cannot be recovered from in your application.

This often used to imply the horrible "wide net" effect, when one uses too wide a net to catch exceptions (and even sometimes never dealt with them in order to get rid of them... but this never happens anymore :P ).

One interesting and possibly easy to integrate evolution to the java language would be the possibility to catch multiple exceptions in one go as follows:

catch([MyException,AnotherException] e){
    throw new WrapperException("Something bad occured in my code, but I won't deal with it, though this gives you a context ;)",e);
}


In this case, in current java constructs, this would end up with:

catch(MyException e){
    throw new WrapperException("Something bad occured in my code, but I won't deal with it, though this gives you a context ;)",e);
}catch(MyException e){
    throw new WrapperException("Something bad occured in my code, but I won't deal with it, though this gives you a context ;)",e);
}


Or more probably because nobody likes repeated code:

catch(MyException e){
    dealWithException(e);
}catch(MyException e){
    dealWithException(e);
}


Or even for lazy people:

catch(Exception e){
    throw new WrapperException("Something bad occured in my code, but I won't deal with it, though this gives you a context ;)",e);
}


I vote for it... do you? ;)

2 commentaires:

David Dossot a dit…

I guess I am pretty lazy because when I have a dependency that forces me to deal with more than a couple of checked exceptions, I catch wide (java.lang.Exception), wrap and re-throw (or log and swallow).

This is unfortunate because there are situations where I want to catch wide (for example, to prevent a caller to receive any exception): it is impossible, by reading the code, to figure out if I am catching wide on purpose or because the called methods are throwing too many checked exceptions (unless I document it).

So: yeah, let's add more syntactic sugar to the Jav!

Anonyme a dit…

Hello Guru, what entice you to post an article. This article was extremely interesting, especially since I was searching for thoughts on this subject last Thursday.

rH3uYcBX