开发者

how to handle exception if finally follows try block

开发者 https://www.devze.com 2023-01-23 06:33 出处:网络
If i put only finally without catch block how exception will be h开发者_运维问答andledThe exception will be passed up the call stack, as if the your try block did not exist, except the code in the fin

If i put only finally without catch block how exception will be h开发者_运维问答andled


The exception will be passed up the call stack, as if the your try block did not exist, except the code in the finally will be executed.

Some example code

try {

   // an exception may be thrown somewhere in here

}
finally {
   // I will be executed, regardless of an exception thrown or not
}


Your exception will not be caught but the 'finally' block will be called and executed eventually. You can write a quick method as below and check it out :


public void testFinally(){
        try{
            throw new RuntimeException();

        }finally{
            System.out.println("Finally called!!");
        }
    }


If i put only finally without catch block how exception will be handled

In that situation, the exception will not caught or handled. What happens, depends on what happens in the finally clause.

  • If the statement sequence in the finally clause completes "normally", the original exception will continue propagating.
  • If the statement sequence in the finally clause completes "abruptly" for some reason then the entire try statement terminates for that reason. Abrupt terminations include throwing an exception, executing a return, break or continue. In this case, the original exception is lost without ever being "handled".

This has some rather interesting consequences. For example, the following squashes any exceptions thrown in the try block.

public void proc () {
    try {
        // Throws some exception
    } finally {
        return;
    }
}

The details of try statements with finally clauses are set out in JLS 14.20.2

0

精彩评论

暂无评论...
验证码 换一张
取 消