Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use finally instead of code after catch [duplicate]

Why do this

} catch (SQLException sqle) {     sqle.printStackTrace(); } finally {     cs.close();     rs.close(); } 

Instead of this

} catch (SQLException sqle) {     sqle.printStackTrace(); } rs.close(); cs.close(); 
like image 517
code511788465541441 Avatar asked Jan 14 '11 14:01

code511788465541441


People also ask

What is the purpose of finally in try catch?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.

Why should I use finally?

Why finally Is Useful. We generally use the finally block to execute clean up code like closing connections, closing files, or freeing up threads, as it executes regardless of an exception. Note: try-with-resources can also be used to close resources instead of a finally block.

What is a benefit of putting code in a finally block?

But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break . Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Why might a Finally block be necessary?

Why to use "finally" block in C#? By using a finally block , you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block . It is just to ensure releasing of all the valuable resources even if the code executed correctly or with an exception.


2 Answers

Because if an exception gets thrown no code after the try block is executed unless the exception is caught. A finally block is always executed no matter what happens inside your try block.

like image 92
JUST MY correct OPINION Avatar answered Sep 22 '22 20:09

JUST MY correct OPINION


Look at your catch block - it's going to throw DAOException. So the statements after your catch block aren't going to be executed even in the sample you've given. What you've shown (wrapping one exception in another) is one common pattern - but another possibility is that the catch block "accidentally" throws an exception, e.g. because one of the calls it makes fails.

Additionally, there may be other exceptions you don't catch - either because you've declared that the method throws them, or because they're unchecked exceptions. Do you really want to leak resources because an IllegalArgumentException got thrown somewhere?

like image 41
Jon Skeet Avatar answered Sep 21 '22 20:09

Jon Skeet