dwz
dwz

Reputation: 385

Java try-finally construction

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.

Upvotes: 1

Views: 950

Answers (10)

Peter
Peter

Reputation: 5798

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;
    }    
  }

Upvotes: 2

fsaftoiu
fsaftoiu

Reputation: 375

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.

Upvotes: 2

mergeconflict
mergeconflict

Reputation: 8276

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.

Upvotes: 3

user963666
user963666

Reputation:

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     
}

Upvotes: 2

SingleShot
SingleShot

Reputation: 19131

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).

Upvotes: 2

Hachi
Hachi

Reputation: 3289

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

Upvotes: 2

F.J
F.J

Reputation: 243

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.

Upvotes: 2

Brendan Long
Brendan Long

Reputation: 54242

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)

Upvotes: 2

filip-fku
filip-fku

Reputation: 3265

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   
}

Upvotes: 2

Prince John Wesley
Prince John Wesley

Reputation: 63698

Some of the common scenarios:

  1. Prevent resource leak:
    Close IO streams and DB connections
  2. Message logging

Upvotes: 2

Related Questions