I had to answer this question with some code:
Suppose I wrote the following method specification:
public void manipulateData ( ) throws java.sql.SQLException, java.sql.SQLDataException
You are writing code for a database program that will use this method and you want to handle each specifically. What should the try/catch clause look like?
You can use no-ops-- empty blocks {}--for the catch clause contents.
We are only interested in the syntax and structure of the statements here.
I answered with this:
try { } catch(java.sql.SQLException e) { } catch(java.sql.SQLDataException e) { }
He did not accept the answer for this reason:
"Your catch clauses are in the wrong order. Can you explain why the order matters?"
Is he correct in his answer?
If I'm not mistaken, subclasses of Exceptions should be caught first.
The order is irrelevant unless one of the exceptions named in a catch handler inherits from another exception named in another handler, in which case the more-derived catch should come first (or it will never be called).
Table 2.16 shows that all exceptions have an associated priority, with: a lower priority value indicating a higher priority. configurable priorities for all exceptions except Reset, HardFault, and NMI.
A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
Yes he is correct. As you can see in the Javadoc, SQLDataException
is a subclass of SQLException
. Therefore, your answer is wrong, since it would create a block of unreachable code in the second catch
.
In Java, this code would not even compile. In other languages (e.g. python) such code would create a subtle bug, because SQLDataException
would actually be caught in the first block, and not in the second one (as would be the case if it was not a subclass).
Had you answered catch(java.sql.SQLException | java.sql.SQLDataException e) { }
, it would still be incorrect, since the question asks to handle each exception specifically.
The correct answer is in Grijesh's answer
In Java you have to put the least inclusive Exception first. The next exceptions must be more inclusive (when they are related).
For instance: if you put the most inclusive of all (Exception) first, the next ones will never be called. Code like this:
try { System.out.println("Trying to prove a point"); throw new java.sql.SqlDataException("Where will I show up?"); }catch(Exception e){ System.out.println("First catch"); } catch(java.sql.SQLException e) { System.out.println("Second catch"); } catch(java.sql.SQLDataException e) { System.out.println("Third catch"); }
will never print the message you'd expect it to print.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With