Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting try catch finally block inside another finally block

Tags:

java

try-catch

 try {  } catch() {}  finally {      try {      } catch() { }      finally { }  } 

Is it good to have the code like above?

like image 968
Saurabh Kumar Avatar asked May 23 '11 10:05

Saurabh Kumar


People also ask

Can we write finally block inside another finally block?

Yes, you can do this.

Can you use a try and catch inside a finally block?

No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed.

Is it possible to take 2 finally blocks for the same try?

You can only have one finally clause per try/catch/finally statement, but you can have multiple such statements, either in the same method or in multiple methods. try.

Can there be a nested try-catch block inside a try-catch block?

Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.


2 Answers

Yes, you can do this.

Actually, you are even required to do it when dealing with streams you want to close properly:

InputStream in = /* ... */; try { } catch (...) { } finally {     try {         in.close();     } catch (...) {     } finally {     } } 

I don't see any case in which this would be a bad practice

like image 171
Vivien Barousse Avatar answered Sep 22 '22 23:09

Vivien Barousse


For readability you can factor out the nested try-catch in to a separate method, like:

  try{   }catch(){}   finally{     cleanup();   } 

And the second try-catch can be inside the cleanup method.

To support the above pattern in IO package, JAVA6 introduces a new class called Closeable that all streams implement, so that you can have a single cleanup method as follows:

public static boolean cleanup(Closeable stream) { try{     stream.close();     return true;   }catch(){     return false;   } } 
like image 26
Suraj Chandran Avatar answered Sep 24 '22 23:09

Suraj Chandran