finally block and Exception handling -- Java

来源:互联网 发布:no sleep for mac下载 编辑:程序博客网 时间:2024/05/29 13:18

The finally block, if used, is placed after a try block and the catch blocks that follow it. The finally block contains code that will be run whether or not an exception is thrown in a try block. 

//Syntax of exception handlingpublic void someMethod(){       Try{             // some code       }       Catch(Exception x){             //throw exception code      }       Catch(Exception y){              // throw exception code       }        Finally{              // this code will be executed whether or not an exception is thrown or caught.        }}

Three possibilities when the code in the try - catch - finally blocks is run:

1. The try block runs to the end and no exception is thrown. In this case, the finally block is executed after the try block. 

2. An exception is thrown in the try block and is caught in on of the catch blocks positioned after the try block. In this case, the finally block is executed after the catch block is executed.

3. An exception is thrown in the try block and there is no matching catch block in the method to catch the exception. In this case, the method invocation ends and the exception object is thrown to the enclosing method. However, the finally block is executed before the method ends. 

0 0
原创粉丝点击