Get Time
Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings
View: Flat (newest first)  | Threaded  | Tree
Previous Thread  |  Next Thread
How to throw exceptions to be determined at runtime using Java 1.5 Generics feature? | Reply
Can anyone demonstrate how any exception to be determined at runtime only be thrown from a method using Java 1,5 generics feature.
Please provide wiht some code snippet.

Thanks in advance,
Re: How to throw exceptions to be determined at runtime using Java 1.5 Generics feature? (response to post by sachin_ks) | Reply
I'll take a stab at answering this.

The type information in generics is only there in java source files, it's not present in the class files. It's basically just there so that the compiler and your IDE can keep you from making mistakes. So if I have an ArrayList<Integer>, there isn't a way to tell it's an ArrayList<Integer> at runtime, but you can still tell that it's an ArrayList. For an exception, you just want to tell what type the exception is though, you don't need to get any information about generics since exceptions don't use generics (at least I don't know of any that do...) If you want to determine the type of something at runtime, you can use instanceof.

So for example:
//Number n could be a Double or could be an Integer, we don't know yet.
Number n = getNumber(); 
if(n instanceof Double){
	//Do something with it		
} else if (n instanceof Integer){
	//Do something else		

If you're trying to catch multiple types of exceptions though, you can use multiple catch blocks. Here's an example:
public class Test {
	public static void myMethod() throws Exception{
		if(Math.random() < .3) throw new RuntimeException();
		if(Math.random() < .5) throw new FileNotFoundException();
		throw new IOException();
	public static void main(String[] args){
		try {
		} catch (FileNotFoundException e){
			System.out.println("First block caught " + e.getClass().getName());
		} catch (IOException e){
			System.out.println("Second block caught " + e.getClass().getName());
		} catch (Exception e) {
			System.out.println("Third block caught " + e.getClass().getName());

Notice that because FileNotFoundException is a subclass of IOException, I need to put the FileNotFoundException catch first. If I put it after the IOException block, it would never do anything, since all the FileNotFoundExceptions would just get handled by the IOException block. An alternative way to do it would be just catch Exception and handle things from there using instanceof.