Saturday 28 November 2009

Java Exceptions: Using Exception's Sub Classes

Syntax of try-catch

try
{

//code which throws some exception
}

catch(XException xe)
{


}
where X is type of exception.

In catch, we have to pass type of exception which is thrown by the code in above try
block.If we know the exact type of excepton thrown, we should use it in catch, as:

catch(SQLException se)
{


}


But what if we are not sure about type of exception thrown? Here is the solution:



catch(Exception e)
{


}


Exception is superclass of all Exception classes. So a reference of Exception can catch all type of exceptions.
So whatever is the exception type, it will catch it and will not give any error.
To know the type of exception, we can print it:

catch(XException e)
{
System.out.println("Exception type: "+e);

}


Caution: If we are using multiple catch blocks for a single try, always put superclass before subclass, as:

try
{

// code here
}

catch(XException xe)
{


}

catch(Exception e)
{


}

where XException may be any exception as SQLException,ClassNotFoundException etc.

Putting Exception before XException will produce error.


try
{

// code here
}

/* this will give compilation error
catch(Exception e)
{


}

catch(XException xe)
{


}

*/