Wednesday, March 25, 2009

Java 7:Multiple exception catch block

Java 7 proposes a new syntax for catching multiple exceptions in a single catch block (http://www.javac.info/Multicatch.html). It looks like a neat feature to have and the new syntax is definately better than having multiple catch blocks with the same exception handling code.
So instead of -

try{
// Some code that throws ServiceException and WebsiteException
}
catch(ServiceException exception) {
Logger.Log(exception);
throw ApplicationException(exception);
}
catch(WebsiteException exception){
Logger.Log(exception);
throw ApplicationException(exception);
}

we will be able to write -

try{
// Some code that throws ServiceException and WebsiteException
}
catch(WebsiteException | ServiceException exception) {
Logger.Log(exception);
throw ApplicationException(exception);
}

So, we will be able to get rid of duplicate exception handling code and will make our code little simpler. Its a pretty obvious change and ideally it should have been identified and fixed before.

This new feature is useful, but how much ? I think this is trying to solve the problem that should not exist. In most of the cases, you should not be throwing more than one checked exception.It will happen if we are exposing the implementation of method and rethrowing the exceptions from called methods.
Even if we have more than one exceptions, we may want to handle them in different ways. So we can not combine multiple catch blocks.
Apart from that, whole lot people in java devs community, including me, believes that checked exceptions should not be used at all. Checked exceptions forces developer to write the exception handling code even when it is not required. Exception handling code gets mixed up with the business logic. This leads to cluttered and unreadable code. Worst part is that checked exceptions create dependency between a method that throws exception and all other methods that directly or indirectly calls that. It makes caller of the method depends on the implementation details of the method. And after coding in C# (which doesn't have checked exceptions) for 2 years, i doubt whether checked exceptions are required in language at all.
Looks like this is nice to have but not so useful (lame?) features in Java 7.

15 comments:

Anonymous said...

Consider having something like this (a very stupid example):

try {
...
} catch (MyException e) {
System.out.println(e.getMessage());
System.out.println(e.getCause().getMessage());
} catch (MyOtherException e) {
System.out.println(e.getMessage());
System.out.println(e.getCause().getMessage());
}

So you want to run the same code on two or more exceptions. With pre-7 Java you have to either duplicate the code or create some temporary variable to hold the state and create an if-block afterwards...

Dan said...

You mention that, in most cases, a method should throw only one type of exception. I think that a method that can fail in two different ways should throw two different kinds of exceptions. This way, callers can detect which failure occurred, and take appropriate action. If only one kind of exception is thrown, detecting the cause of the error becomes more difficult.

It might make sense to have a base exception class that those two exceptions derive from. Then, you can catch the general exception if that makes sense, or a specific exception if you need fine control.

Overall, though, I agree that most methods only need to throw one kind of exception. Still, I think this is a welcome change to the Java language.

Riaan Nel said...

What would the type of 'ex' be when you have a catch block that looks like this?

...catch (Exception 1 | Exception 2 ex)...

The only 'valid' option in my opinion, would be for 'ex' to be of type Exception, as either ex.doException1Method() or ex.doException2Method() will always be invalid. If we take this into account, is the proposed method really any better than just having ...catch (Exception ex)...?

Dan said...

When you have a catch block like that, the compiler can determine the most-specific common base class. If you try to catch IOException and AWTExcepion, you would get an Exception. But if you try to catch a FileNotFoundException and an UnknownHostException, you would get an IOException. I don't know if they actually plan to implement it this way, but I hope they do.

Now, you might say that instead of writing:

catch (IOException | AWTExcepion ex)

developers should just write:

catch (Exception ex)

I would point out that these behave in very different ways. In particular, the second version will also catch RuntimeExceptions. I rarely catch RuntimeExceptions. If I ever do need a generic catch(Exception) block, I usually test for and rethrow any RuntimeExceptions that occur.

But most importantly, this new syntax doesn't remove features; it only adds features. If you don't need to catch multiple exceptions, then don't use it. I don't think that this construct will be very common, but I think it will be handy when it is needed. It's relatively intuitive to write, and very intuitive to read. All in all, I don't see any downsides to them adding it to the language.

zolv said...

"Apart from that, whole lot people in java devs community, including me, believes that checked exceptions should not be used at all. Checked exceptions forces developer to write the exception handling code even when it is not required."

Definitely all of You (Java dev comunity) are "weak-typers". Were You programming in PHP before Java? I'm sure You did. If You like more RuntimeException more than checked exceptions in Java then Your code is full of problems. Runtime exception generally means bug in the code - nothing more, nothing less.

What does it mean that exception handling is not required? If exception handling is not required - then exception throwing is not required. That means - method is implemented wrong.

Amey said...

Sorry for such a late reply, but it's better than never :)

It is a welcome change to the language, which makes java a little bit better. There are scenarios where this can save few lines of code and there is definitely no downside to it.

@Anonymous - This is useful when you want to write the code similar to your example. However, how many times you write code like that in real systems ? How many times you want to catch different exceptions and do the same thing ? As I said before, I am not denying the fact that this is a useful feature, it's just not a very exciting new feature.

@Daniel - I completely agree with you that this is a nice little improvement to the language syntax. And you are also right about the type of exception in multi-catch block. I have explained the same in a new blog on multi-catch statements in Java 7.

@z - "If You like more RuntimeException more than checked exceptions in Java then Your code is full of problems." - IMHO, that's not true.
Languages like C#, Ruby doesn't have checked exceptions at all, it doesn't mean that all the code written in those languages is buggy. In fact, Java is the only mainstream language which has checked exceptions. You can find many articles about why checked exceptions is not a great idea.

There are scenarios where using checked exception is a good idea. However, "Runtime exception generally means bug in the code" is definitely not true.

This blog was written more than three years before and I have now published a new blog entry with other details about how multi-catch works in the java 7.

NPE633 said...
This comment has been removed by the author.
NPE633 said...

A quick read, highly suggested:

http://onjava.com/onjava/2003/11/19/exceptions.html

The Java developers (IE. those who develop Java, not "in" Java, had a reason for everything they did). Caught exceptions are very useful for enforcing a contract. If a technical lead is writing up some interfaces and hollow code for another developer to fill in, he/she may decide to have checked exceptions in the interface to force the developer to handle them.

I personally think that this new feature is just a bell/whistle: this can easily be handled by a private function. Honestly: the more things there are to break, the more things break.

Sankar said...

Interesting and good feature. It reduce the lot of typing for developers.


Sankar.lp
java training

Anna said...

Great and Useful Article.

Online Java Training

Online Java Training from India

Online Java Training

Online Java Training From India

Java Training Institutes in Chennai

Java Training in Chennai

Shivam Kumar said...

Very Nice ... visit more Exception Examples

Unknown said...

Excellent Blog very imperative good content, this article is useful to beginners and real time Employees...Oracle Training in Chennai
Oracle Training Institute in Chennai

pooja said...

I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.
Hadoop Training in Chennai
Hadoop Training in Bangalore
Big data training in tambaram
Big data training in Sholinganallur
Big data training in annanagar

Unknown said...

Hi there I am so thrilled I found your website, I really found you by mistake, while I was browsing on Yahoo for something else, Anyhow I am here now and would just like to say thanks a lot for a tremendous post and an all-round exciting blog (I also love the theme/design), I don’t have time to go through it all at the minute but I have saved it and also added in your RSS feeds, so when I have time I will be back to read more, Please do keep up the awesome job.
python Course in Pune
python Course institute in Chennai
python Training institute in Bangalore

dras said...

Good post..
inplant training in chennai
inplant training in chennai
inplant training in chennai for it.php
Australia hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
australia web hosting
denmark web hosting