Could someone explain me some situation (example) when we can use this construction?
try{
//dangerous code here
} finally {
//always called
}
I really understand how it works but newer use in real situation.
Pretty much any time you have something like a Closeable, where you need to explicitly call close() to release the underlying resource, you want to put that call in a finally block, like:
FileReader f = whatever();
try {
// do some stuff with f
return;
}
finally {
f.close();
}
Even if no exception is thrown, and the return inside the try block is run, the resource will still be closed correctly.
try {
isWorking = true
//doStuff that might or might not succeed
} finally {
isWorking = false;
}
another example:
public void actionPressed()
{
if( isLoading )
return;
try {
isLoading= true;
doTheLoad);
} finally {
isLoading = false;
}
}
Some of the common scenarios:
Prevent resource leak:
Close IO streams and DB connections
Message logging
You might use it close database connections or any other resource - a file, hardware port, etc.
try{
// Do something I care about
} finally {
// Make sure we clean up, regardless of success or failure
}
Here's an example:
InputStream in = new FileInputStream(...);
try {
/ * use in here */
} finally {
in.close();
}
Basically, no matter what happens, in will always be closed. Without this, in could stay open until the garbage collector collects it (could be a long time). This is a problem because:
There is a limit on the number of files / network connections you can have open at once
Open network connections will continue to tie up resources on the remote end too (DB connections are a good example)
Closing an input stream also flushes it generally (flushing writes anything in the inputstream's buffer)
For instance when you read a file:
InputStream is = new FileInputStream("...");
try {
// do stuff
}
finally {
is.close();
}
This way your file is always closed, even if there is an exception.
openFile();
try {
int i = Integer.parseInt(someString);
String sub = someString.substring(2);
System.out.println(i+sub);
}
finally {
closeFile();
}
as you can see, there might several Exceptions be thrown during a code passage and you possibly don't want to catch every of them.
also there could an Error be thrown, which you should not catch!
in any way you want to close your file, before the method ends, so you put that in the finally-block
Look at this article, Java Exception Handling - Basics. Here described clearly about exception and where it is used.
This is a very common pattern:
InputStream stream = // acquire stream...
try {
// do stuff with stream that might throw...
}
finally {
IOUtils.closeQuietly(stream);
}
Note, IOUtils is a library from the Apache Commons project. You should always close the stream in a finally. closeQuietly eats any exceptions that might be thrown while trying to close the stream (which is OK because you can't do anything about it).
Especially we can use for data base connection close related code in finally block. if program throws any exception in this case DB connection will release .
This is example in JDBC.same can be applicable in session.close() in Hibernate.
try{
//dangerous code here
} catch(Exception e){
//Do some thing releted to your exception
} finally {
//close DB connection or close your hibernate session.
//always called
}
Well, let's say you open a connection to a database and make some queries. If a SQLException is raised by one of the queries, you're supposed to close the connection before doing something else. If no exception is raised, you're still supposed to close it.
So the try {} catch () {} is there to catch those SQLExceptions and do something about them, while the finally {} is there to close the connection in either case.
This would be a very common scenario, but the same is true with any resource that needs to be freed no matter what happens while using it.
Related
I've got a doubt about using the try/catch/finally clauses,let me explain:
I know that every method which declares an exception specification in its declaration has to be surrounded (in a calling method) with a try block,followed by a catch block that can capture that exception (unless I don't declare the calling method throwing an exception as well). If the calling method has other statements after the try-catch, those are executed regardless of what happens (exception thrown or not). So if I have the following code:
public class ExceptionCall {
Throwing t = new Throwing();
public void methodTry(){
while(true){
try {
if (t.flag++==0)
t.throwing();
System.out.println("no exception");
}
catch (MyException e) {
e.printStackTrace(System.err);
System.out.println("working on it!");
}
finally{
System.out.println("finally clause");
}
System.out.println("out");
if (t.flag==2)
break;
}
}
}
Here Throwing has a method called (guess what :) ) throwing() which is declared to throw a MyException exception, and has a public field called flag containing an int initialized to 0 to provide a sort of condition checking.
So for a couple of times the code outside the guarded region is executed no matter what happens in the try block.
So my question is, what is the finally block for?? I mean, I know it comes in handy when the calling method returns from the try or the catch block (in this case I could have a break statement inside the catch and the finally would be executed), but in a case like this what's the difference??
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. 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.
See : https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
Finally block is used to handle those resources that need you to make some action at the end of the statement no matter what happens in the code.
For example: readers or streams are resources that must be closed after it's use, but exceptions can happen during it's usage, so where you close them???
Here is where finally clause becomes really handy:
FileReader reader;
try {
reader = new FileReader("someNonExistingFile");
} catch (FileNotFoundException e) {
// handle FileNotFoundException
e.printMessage();
} finally {
// reader MUST BE CLOSED ALWAYS, so FINALLY, CLOSE IT
reader.close();
}
In this example, you need to close reader always (if file exists and if file doesn't) so, instead of closing it twice (in try and in catch) you use finally.
Further info and examples of finally here. Also check try with resources (Java 7+).
Eclipse 4 gives a warning which says the stmt may potentially not be closed and cause a resource leak:
class Test {
public void test() {
PreparedStatement stmt = null;
try {
stmt = HibernateSession.instance().connection().prepareStatement("");
} catch (final SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
try {
stmt.close();
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
}
Under which circumstance would that happen?
I guess the conclusion here is: this is an Eclipse bug?
A leak is possible if an exception is thrown when you call stmt.close() in the finally block.
The problem was that in your finally block an exception might potentially occur, which would prevent stmt from closing.
One workaround is that you can replace everything in the finally block with:
JDBCUtilities.close(stmt);
See the docs for JDBCUtilities.close. As you can see, no exception will be thrown using this utility method so you don't need to worry about resource leak. One additional benefit is that the utility method handles the null case for stmt as well so we don't need to code it ourselves.
Actually, it is good practice to use JDBCUtilities.
You need to be using Java 7's try with resources or a try-finally block:
try(stmt = HibernateSession.instance().connection().prepareStatement("")) {
}
This warning will be generated on types that inherit from AutoCloseable that are not guaranteed to be closed. (Or possible Closeable, I forget which).
Now that I see what you're asking, just write less complicated code.
Foo f = null; // don't do this, but it's what you're doing
f = new Foo();
Is what you're doing, and you found one of several situations where you actually have to pay a penalty for this extraneous work.
Furthermore your try/finally should be clean. .close() can't throw, why are you catching?
try { // don't do this
stmt.close();
}
catch(SQLException exc) {
}
Should generate an Eclipse warning telling you that you're catching something that doesn't throw. That might even be a compile error, not sure, but sounds like you would benefit from playing with Eclipse > Preferences > Compiler and reviewing what warnings are intelligent. If you don't understand a warning, google it and see if it would be helpful to you, don't just skip over it. (sort of like you did with this one).
I have an app that uses JSoup to connect to a web server, and it works fine. Unfortunately, the said web server isn't very reliable. I get SocketException because of time-out connection quite often. I make the connection in a modified IntentService, and I just simply repeat onHandleIntent(intent) in the catch(Exception e) block.
catch(Exception e){
Log.d(Tag, "in catch Exception block...");
onHandleIntent(intent);
}
Theoretically, this should work. But sometimes, I get stack over flow error, and the app ended quite ungracefully. So, what can I do to make it better?
I want to continue to call onHandleIntent, so, maybe I have to call it in iteration instead of recursively. If you can give me advice on how to implement this iteratively, it would be very helpful. Thanks!
I want to continue to call onHandleIntent, so, maybe I have to call it in iteration instead of recursively.
That is correct. If you handle this recursively, a server that continually times out will inevitably result in a stack overflow.
If you can give me advice on how to implement this iteratively, it would be very helpful. Thanks!
Something like this:
for (int tries = 1; ; tries++) {
Connection conn = null;
try {
// attempt to connect
// do stuff
} catch (SocketException ex) {
if (/* timed out */ && tries < MAX_TRIES) {
continue;
}
// report exception
} finally {
if (conn != null) {
// close it
}
}
break;
}
(Maybe someone can think of a less "clunky" way to write this ...)
This question already has answers here:
Why use finally
(9 answers)
Closed 1 year ago.
As far as I can tell, both of the following code snippets will serve the same purpose. Why have finally blocks at all?
Code A:
try { /* Some code */ }
catch { /* Exception handling code */ }
finally { /* Cleanup code */ }
Code B:
try { /* Some code */ }
catch { /* Exception handling code */ }
// Cleanup code
What happens if an exception you're not handling gets thrown? (I hope you're not catching Throwable...)
What happens if you return from inside the try block?
What happens if the catch block throws an exception?
A finally block makes sure that however you exit that block (modulo a few ways of aborting the whole process explicitly), it will get executed. That's important for deterministic cleanup of resources.
Note that (in Java at least, probably also in C#) it's also possible to have a try block without a catch, but with a finally. When an exception happens in the try block, the code in the finally block is run before the exception is thrown higher up:
InputStream in = new FileInputStream("somefile.xyz");
try {
somethingThatMightThrowAnException();
}
finally {
// cleanup here
in.close();
}
You may want to put the code that you want to anyway get executed irrespective of what happens in your try or catch block.
Also if you are using multiple catch and if you want to put some code which is common for all the catch blocks this would be a place to put- but you cannot be sure that the entire code in try has been executed.
For example:
conn c1 = new connection();
try {
c1.dosomething();
} catch (ExceptionA exa) {
handleexA();
//c1.close();
} catch (ExceptionB exb) {
handleexB();
//c1.close();
} finally {
c1.close();
}
Finally always gets executed, where as your code after the catch may not.
Even though our application is closed forcefully there will be some tasks, which we must execute (like memory release, closing database, release lock, etc), if you write these lines of code in the finally block it will execute whether an exception is thrown or not...
Your application may be a collection of threads, Exception terminates the thread but not the whole application, in this case finally is more useful.
In some cases finally won't execute such as JVM Fail, Thread terminate, etc.
Still scrolling down? Here you go!
This question gave me tough time back a while.
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
what would be printed in the above scenario?
Yes guessed it right:
ex.Message--whatever it is (probably attempted division by zero)
Finally block
After finally
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block");
}
console.writeline("After finally");
What would this print? Nothing! It throws an error since the catch block raised an error.
In a good programming structure, your exceptions would be funneled, in the sense that this code will be handled from another layer. To stimulate such a case i'll nested try this code.
try
{
try
{
int a=1;
int b=0;
int c=a/b;
}
catch(Exception ex)
{
throw(ex);
}
finally
{
console.writeline("Finally block")
}
console.writeline("After finally");
}
catch(Exception ex)
{
console.writeline(ex.Message);
}
In this case the output would be:
Finally block
ex.Message--whatever it is.
It is clear that when you catch an exception and throw it again into other layers(Funneling), the code after throw does not get executed. It acts similar to just how a return inside a function works.
You now know why not to close your resources on codes after the catch block.Place them in finally block.
Because you need that code to execute regardless of any exceptions that may be thrown. For example, you may need to clean up some unmanaged resource (the 'using' construct compiles to a try/finally block).
There may be times when you want to execute a piece of code no matter what. Whether an exception is thrown or not. Then one uses finally.
finally ALWAYS executes, unless the JVM was shut down, finally just provides a method to put the cleanup code in one place.
It would be too tedious if you had to put the clean up code in each of the catch blocks.
If catch block throws any exception then remaining code will not executed hence we have to write finaly block.
finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
I am using JDBC to retrieve data from a database. I understand that a Statement needs to be closed after it is used. However, I keep run into the same error telling me that no operation is allowed after the statement is closed. The structure of my code is like
public void foo() {
Statement;
try {
} catch{
}
Statement.close();
}
In my code, I need to call this function repeatedly. I was wondering where to close the Statement.
Thanks
According to the Javadocs:
Statement.close() Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.
Which means you should close it after you done and not planning to use it again. I would, actually pay more attention to closing your Connection.
In your method which you say you call repeatedly you are calling Statement.close() which means that you can only use it once since after the first call you Statement is closed and cannot be used anymore.
It would be nice to see some of your code if you want a better answer
Note that JDBC resources should always be closed, so, its better to put that to the 'finally' block.
You can also consider Spring DAO usage - it is a thin wrapper on top of JDBC and covers most of JDBC boilerplate stuff.
ResultSets also need to be closed.
It sounds like you might be doing something like accessing a Blob, the Blob object often goes back through the connection to read the byte data from the database. So read all of the byte[] data before you close the connection. If that's not possible because there's too much data and you are trying to stream the bytes then you're just going to have to stick the connection somewhere safe and call close on it later.
Close statements should go into finally blocks, and be null protected - but it's such common and ugly code so stick in a static method somewhere.
public List someMethod() {
Statement stmt;
ResultSet rset;
try {
stmt = con.createStatement();
rset = stmt.executeQuery(....);
List resultList = ...create a list
// get the data from the rset
return resultList;
} catch (SQLException ex) {
throw new MyDatabaseException(ex);
} finally {
}
}
public class DatabaseUtils {
public void close(Statement stmt, ResultSet rset) {
try {
if (rset != null) {
rset.close();
}
} catch (SQLException ex) {
throw new MyDatabaseException(ex);
} finally {
if (stmt != null) {
throw new MyDatabaseException(ex);
}
}
}
}