Steven Levine
Steven Levine
~1 min read

Tags

How many times have you written code where you have something along the lines of:

try { do something interesting ... }
    catch (X1 e1) { close(); }
    catch (X2 e2) { close(); }
    catch (X3 e3) { cleanup();
}

It is cumbersome to have to catch X1 and X2 separately even though they perform the same action if an Exception is raised. Wouldn’t it be nice if there was a way to catch both X1 and X2 with one single catch block?

Enter the Java 7 proposal for Multi-Catch statements. If/when this proposal makes it in to the language, it would eliminate the need to have a catch statement for each Exception. It facilities a mechanism to catch multiple Exceptions, and then perform the same action on them eliminating the need to have one catch per Exception thrown.

try { do something interesting ... }
   catch (X1, X2 e1) { close(); }
   catch (X3 e ) { cleanup(); }

Now isn’t this code much cleaner? Let’s hope it makes it in to the next version of Java.