Java Exceptions: Using Exception’s Sub Classes

Syntax of try-catch

//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:

// 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.

// code here

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

catch(XException xe) { }


  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: