Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

correct order of declaring Exceptions.  RSS feed

 
aman hindustani
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello to all..

I got a doubt..in which order ..we need declare exeptions..in the catch block ..first checked, or unchecked excpetion.

please tell me the order for this..

SQLException ,NumberFormatException,NullPointerException.

Thanks
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java In General (Beginner)
This is not a servlet question.
 
shan sundaram
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The order may be
NullPointerException, NumberFormatException,SQLException,....,Exception.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whether an exception is checked or unchecked doesn't affect the ordering. Instead what matters is inheritance. If you need to catch two exception types, and one is a subtype of the other -- for example, FileNotFoundException and IOException (the first is a subclass of the second) then you need to put the subclass first, or the other catch block would catch it. The compiler will generally refuse to compile the code if you do it the wrong way, as then the later catch blocks would be unreachable.
 
aman hindustani
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks mr Eanest.......for u reply....
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The ones to be extra-careful of are Exception and Throwable.

There are not very many cases where it is valid to catch Exception (a lot of the time, people are just being lazy and not listing the true set of exceptions). There are only a very few cases where it is valid to catch Throwable.

However, if you do decide to catch Exception or Throwable, be aware that you will catch things that would normally sail straight on through, such as RuntimeException (and all subclasses) and Error (and all subclasses). That is often not what you want.

I've often thought it is a shame that Java checked exceptions descend from the same superclass (Exception) as RuntimeException. Does anyone know why they didn't make Exception abstract and then introduce a CheckedException subclass, from which all checked exceptions would descend?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!