I had to answer this question with some code:
Suppose I wrote the following method specification:
public void manipulateData ( ) t
Order matter when catching exceptions because of following reason:
Remember:
e is a reference variablecatch(ExceptionType e){ }
The lowercase character e is a reference to the thrown (and caught) ExceptionType object.
Reason why your code not accepted?
It is important to remember that exception subclass must come before any their superclasses. This is because a catch statement that uses a superclasses will catch exception of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass.
Further, in Java, Unreachable code is an error.
SQLException is supperclass of SQLDataException
+----+----+----+
| SQLException | `e` can reference SQLException as well as SQLDataException
+----+----+----+
^
|
|
+----+----+----+---+
| SQLDataException | More specific
+----+----+----+---+
And if your write like having error Unreachable code (read comments):
try{
}
catch(java.sql.SQLException e){//also catch exception of SQLDataException type
}
catch(java.sql.SQLDataException e){//hence this remains Unreachable code
}
If you try to compile this program, you will receive an error message stating that the first catch statement will handle all SQLException-based errors, including SQLDataException. This means that the second catch statement will never execute.
Correct Solution?
To fix it reverse the order of the catch statements.That is following:
try{
}
catch(java.sql.SQLDataException e){
}catch(java.sql.SQLException e){
}