Catching Multiple Exceptions in Java JDK 7


I did some experimentation with catching multiple exceptions in Java 7. Given the following class definitions:

// all in individual files for package test
class QException extends Exception {

	public void blah() {
		System.out.println("blah!");
	}
}

class IException extends QException {
	public void a() {
		System.out.println("a!");
	}
}

class OException extends QException {
	public void b() {
		System.out.println("b!");
	}
}

The following compiles and runs:

package test;

import test.IException;
import test.OException;
import java.io.FileNotFoundException;
import java.io.IOException;

class TestMe {
	public static void main(String[] args) {
		try {
			double result = Math.random();
			if(result < 0.3) {
				throw new IException();
			} else if (result < 0.6) {
				throw new OException();
			} else {
				throw new FileNotFoundException();
			}
		} catch (IException | OException | IOException blahException) {
			System.out.println(blahException.getClass().getName());	
//			blahException.blah();	
		}
	}
}

The getName() function prints out test.IException, test.OException, and java.io.FileNotFoundException (depending on the random variable result). If you remove the comments on the .blah() call, it fails to compile. The reason why I have FileNotFoundException thrown but am catching the IOException is that initially I (for some reason) was having to cast the thrown FileNotFoundException to an IOException to have it matched by the IOException in the catch clause.

However, if you have just the two exceptions that are subclasses of QException, then the .blah() call is recognized. So, for interface consideration, the compiler appears to figure out the "greatest common subclass".

package test;

import test.IException;
import test.OException;
import java.io.FileNotFoundException;
import java.io.IOException;

class TestMe {
	public static void main(String[] args) {
		try {
			double result = Math.random();
			if(result < 0.5) {
				throw new IException();
			} else {
				throw new OException();
			}
		} catch (IException | OException blahException) {
			System.out.println(blahException.getClass().getName());	
			blahException.blah();	

		}
	}
}

Leave a Reply

%d bloggers like this: