try { } catch() {} finally { try { } catch() { } finally { } }
Is it good to have the code like above?
Yes, you can do this.
No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed.
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.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
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
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; } }
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