finally.java

来自「JAVA 2应用开发指南」· Java 代码 · 共 55 行

JAVA
55
字号
//finally.java
public class finally
{
	public static void main(String args[])
	{
		try {
            throwException();
        }   
         // catch Exceptions thrown by method throwException
         catch ( Exception exception )
         {
            System.err.println( "Exception handled in main" );
         }   
         doesNotThrowException();
      }   
      // demonstrate try/catch/finally
      public static void throwException() throws Exception
      {
         // throw an exception and immediately catch it
         try {
            System.out.println( "Method throwException" );
            throw new Exception();  // generate exception
          }
catch ( Exception exception )
         {
            System.err.println("Exception handled in method throwException" );
            throw exception;  // rethrow for further processing  
            // any code here would not be reached
         }   
         // this block executes regardless of what occurs in 
         // try/catch
         finally {
            System.err.println("Finally executed in throwException" );
         }   
         // any code here would not be reached
      }   
      // demonstrate finally when no exception occurs
      public static void doesNotThrowException()
      {
         // try block does not throw an exception
         try {
            System.out.println( "Method doesNotThrowException" );
          }   
         // catch does not execute, because no exception thrown
         catch( Exception exception )
         {
            System.err.println( exception.toString() );
         }
finally {
            System.err.println("Finally executed in doesNotThrowException" );
         }   
         System.out.println("End of method doesNotThrowException" );
      }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?