What is the benefit to use “finally” after try-cat

2019-01-14 05:26发布

The "finally" block is always executed when the try-catch ends, either in case of exception or not. But also every line of code outside and after the try-catch is always executed. So, why should I use the finally statement?

Example:

try {
    //code...
} catch (Exception e) {
    //code...
} finally {
    System.out.println("This line is always printed");
}
System.out.println("Also this line is always printed !! So why to use 'finally'?? ");

6条回答
叼着烟拽天下
2楼-- · 2019-01-14 05:54

The most useful case is when you need to release some resources :

InputStream is = ...
try {
    //code...
} catch (Exception e) {
    //code...
} finally {
    is.close();
}

More generally, you use it when you want to be sure your code is executed at the end, even if there was an exception during execution :

long startTime = System.currentTimeMillis();
try {
    //code...
} catch (Exception e) {
    //code...
} finally {
    long endTime = System.currentTimeMillis();
    System.out.println("Operation took " + (endTime-startTime) + " ms");
}

The idea of this finally block always being executed is that it's not the case for the first line following the whole block

  • if the catch block lets some throwable pass
  • if it rethrows itself an exception, which is very frequent
查看更多
干净又极端
3楼-- · 2019-01-14 05:55

The last System.out.println (after the finally block) will only be run if the exception thrown in the try block is actuaclly caught with a catch block and if the execution is not interrupted by e.g. a return statement.

In your example, the finally block will always be run, but the execution will only continue past the finally block if no Error is thrown in the try block (it would not be caught), if no Throwable is thrown in the catch block and there is no other statement, which will interrupt execution.

查看更多
家丑人穷心不美
4楼-- · 2019-01-14 05:58

suppose you are writing in the file and suddenly it creates an exception the how you close the file .then finally help you and also for database transaction finally block helps a lot

查看更多
虎瘦雄心在
5楼-- · 2019-01-14 06:07

finally block's only purpose is to close the resources which you have opened inside try block. resources could be anything like database connections,File writing/reading etc:

Connection conn= null;
try {
 conn= get the db conn;
//do some DML/DDL
}
catch(SQLException ex) {

}
finally {
conn.close();
}
查看更多
叛逆
6楼-- · 2019-01-14 06:14

But also every line of code outside and after the try-catch is always executed

This is incorrect. In case of unchecked exceptions (RuntimeException, Error, and their subclasses) code after finally will not execute.

Take a look at this code

public static void main(String[] args) {
    try{
        someDengerousMethod();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        System.out.println("finally block");
    }
    System.out.println("after finally...");
}
public static void someDengerousMethod(){
    throw new Error("something went wrong");
}
查看更多
做自己的国王
7楼-- · 2019-01-14 06:16

The finally block is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finally block to ensure that resource is always recovered.

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.

More here

查看更多
登录 后发表回答