Application for departure?

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

+7
source share
8 answers

Yes. FileNotFoundException inherited from IOException. First of all, you need to catch subclasses of exceptions.

+8
source

Yes, a specific exception should be written first, wider after that,

As you call all animals first in the room, and after you try to see if there is any person outside

for example

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

Gives you a compile time error

+10
source

Specific exceptions must be detected before a general exception, otherwise you will get an unreachable code error. For example -

 try{ //do something }catch(NullPointerException npe){ }catch(NumberFormatException nfe){ }catch(Exception exp){ } 

If you place a catch Exception block before a catch NullPointerException or NumberFormatException , you get a compile-time error. (Unavailable code).

+3
source

In tangent, I would advise you to think twice if you need all these catch blocks. Are you sure that you are going to interpret the treatment for each case in different ways? If you are just going to print a message, you can catch an IOException to do this.

+2
source

well ... start by subclassing the superclass ... which is the perfect way ... otherwise you get an unattainable code error

+1
source

Oh sure. A more specific exception must be recorded in the first catch block, and general exceptions, such as catch(Exception ex){ex.printStackTrace();} , must be recorded in the final set of the catch block.

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

0
source

IOException - a superclass of the FileNotFoundException class. So, if you put the catch statement for IOException higher than for FileNotFoundException , then the code for the second catch will become unavailable, and the compiler will throw an error for it. The reason is simple: every object of a sub class can be easily accepted by a super class reference .

0
source

IOException is a superclass of FileNotFoundException. Contains a subclass of class ie FileNotFoundException, and then you need to catch an IOException

For example,

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

All Articles