Saturday, November 19, 2011

Exception handling – multiple catch.

Let's talk about the exception handling. Just to ensure that we are standing on the same planet – multiple catch of exception is a situation when we have a method that throws more than one checked exception and we want to handle some of them separetly. The following Java code shows such situation:

import java.util.ArrayList;
import java.util.List;

class Exception1 extends Exception {}
class Exception2 extends Exception {}
class Exception3 extends Exception {}

public class ExceptionHandling {
public static void throwsExceptions() throws Exception1, Exception2, Exception3 {
return;
}

public static void testMethod() {
try {
throwsExceptions();
}
catch(Exception1 e) {
// handle Exception1
}
catch(Exception2 e) {
// handle Exception2
}
catch(Exception e) {
// handle other exceptions.
}
}
}

But what if the logic for handling Exception1 and Exception2 is the same? In this case we get a dirty code duplication. Although, there is a simple remedy for that. What we could do, is to catch a base Exception class and then branch appropriately with if-else statement as the below code snippet presents:

public static void testMethod2() {
try {
throwsExceptions();
}
catch(Exception e) {
if(e instanceof Exception1 || e instanceof Exception2) {
// Do the common handling logic for Exception1 and Exception2
}
else {
// Handle other exceptions
}
}
}

So far so good. We don't have code duplication anymore. Just a note: the above examples use Java language but they also apply to C# - we would face the same issue/remedy when coding in it.
Now you may wonder what more can be done. As for C# not much really. In Java though, there is still some room for improvement. In Java 7 there has been introduced a new multiple catch mechanism so that we can catch multiple exceptions in one catch block! The following code sample shows the solution using Java 7:

public static void testMethod3() {
try {
throwsExceptions();
}
catch(Exception1 | Exception2 e) {
// Do the common handling logic for Exception1 and Exception2
}
catch(Exception e) {
// Handle other exceptions.
}
}

Here we can see how exceptions of type Exception1 and Exception2 are handled in one catch block using the '|' operator.
Summing up – a point for Java :)

No comments:

Post a Comment