user1920811
user1920811

Reputation:

Order of catch statement?

In try-catch syntax, does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Upvotes: 11

Views: 10463

Answers (8)

Pramod Kumar
Pramod Kumar

Reputation: 8014

Specific Exceptions must be caught prior to general exception or else you will get an unreachable code error. For example -

try{
  //do something
}catch(NullPointerException npe){

}catch(NumberFormatException nfe){

}catch(Exception exp){

}

If you put the Exception catch block before the NullPointerException or NumberFormatException catch block, you will get a compile time error. (Unreachable code).

Upvotes: 7

user1920811
user1920811

Reputation:

Yes. The FileNotFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

Upvotes: 9

ShinnedHawks
ShinnedHawks

Reputation: 156

IOException is the super class of FileNotFoundException .So fist catch sub class i.e FileNotFoundException and then you need to catch IOException

For Example,

try{
      // something
   } catch(FileNotFoundException fne){
      // Handle the exception here
   } catch(IOException ioe) {
      // Handle the IOException here
   }

Upvotes: 0

amicngh
amicngh

Reputation: 7899

IOException is the super class of FileNotFoundException. So, if you put the catch statement for IOException above that for FileNotFoundException, then the code for second catch will become unreachable and the compiler will throw an error for that. Reason is simple: every object of a sub class can be easily accepted by a super class reference.

Upvotes: 0

LGAP
LGAP

Reputation: 2463

Yes Of Course. The more specific exception should be written in the first catch block and the generic exceptions like catch(Exception ex){ex.printStackTrace();} should be written in the final set of catch block.

If you try the other way then, your specific exception will be unreachable by the JVM compiler!

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200158

On a tangent, I would advise you to think twice whether you need all those catch blocks in the first place. Are you sure you are going to provide meaningful handling for each case differently? If you are just going to print out a message, you can only catch IOException to do that.

Upvotes: 2

Ahmad
Ahmad

Reputation: 2190

well...start from subclasses to superclass...that's the ideal way..otherwise you will get unreachable code error

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240900

Yes, Specific exception should be written first, broader after that,

Its like you call all the animals first in the room and after you try to see if there is any human outside

For example

try{
  //do something
}catch(Exception ex){

}catch(NullPointerException npe){

}

Will give you compile time error

Upvotes: 11

Related Questions