Java exception handling combat

Using an exception handling - to be able to capture the abnormal

Code 1

public class DealException
{
   public static void main( String[] args )
   {
      try
      // 检查这个程序块的代码
      {
         int arr[] = new int[5];
         arr[10] = 7;   // 在这里会出现异常
      }
      catch( ArrayIndexOutOfBoundsException e )
      {
         System.out.println( "数组超出绑定范围!" );
      }
      finally
      // 这个块的程序代码一定会执行
      {
         System.out.println( "这里一定会被执行!" );
      }
      System.out.println( "main()方法结束!" );
   }
}

2 runs

数组超出绑定范围!
这里一定会被执行!
main()方法结束!

Exception handling using a two - is not able to capture the abnormal

Code 1

public class DealException
{
   public static void main( String[] args )
   {
      try
      // 检查这个程序块的代码
      {
         int arr[] = new int[5];
         arr[10] = 7;   // 在这里会出现异常
      }
      catch( ArithmeticException e )
      {
         System.out.println( "算术异常" );
      }
      finally
      // 这个块的程序代码一定会执行
      {
         System.out.println( "这里一定会被执行!" );
      }
      System.out.println( "main()方法结束!" );
   }
}

2 runs

这里一定会被执行!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at DealException.main(DealException.java:9)

3 Description

For the scene uncaught exception, finally statement block is executed, but the language of the statement after the finally block can not be executed, will be an exception to the JVM to handle, and finally stop running.

Guess you like

Origin blog.csdn.net/chengqiuming/article/details/94828563