欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java異常處理操作實例小結

 更新時間:2019年07月18日 09:24:21   作者:cakincqm  
這篇文章主要介紹了Java異常處理操作,結合實例形式總結分析了java異常處理常見操作情況與相關處理技巧,需要的朋友可以參考下

本文實例講述了Java異常處理操作。分享給大家供大家參考,具體如下:

一 異常處理的使用——能夠捕獲到異常

1 代碼

public class DealException
{
  public static void main( String[] args )
  {
   try
   // 檢查這個程序塊的代碼
   {
     int arr[] = new int[5];
     arr[10] = 7;  // 在這里會出現(xiàn)異常
   }
   catch( ArrayIndexOutOfBoundsException e )
   {
     System.out.println( "數(shù)組超出綁定范圍!" );
   }
   finally
   // 這個塊的程序代碼一定會執(zhí)行
   {
     System.out.println( "這里一定會被執(zhí)行!" );
   }
   System.out.println( "main()方法結束!" );
  }
}

2 運行

數(shù)組超出綁定范圍!
這里一定會被執(zhí)行!
main()方法結束!

二 異常處理的使用——不能夠捕獲到異常

1 代碼

public class DealException
{
  public static void main( String[] args )
  {
   try
   // 檢查這個程序塊的代碼
   {
     int arr[] = new int[5];
     arr[10] = 7;  // 在這里會出現(xiàn)異常
   }
   catch( ArithmeticException e )
   {
     System.out.println( "算術異常" );
   }
   finally
   // 這個塊的程序代碼一定會執(zhí)行
   {
     System.out.println( "這里一定會被執(zhí)行!" );
   }
   System.out.println( "main()方法結束!" );
  }
}

2 運行

這里一定會被執(zhí)行!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at DealException.main(DealException.java:9)

3 說明

對于未捕獲到異常場景,finally語句塊會執(zhí)行,但finally語言塊之后的語句不能執(zhí)行,將異常交給JVM去處理,最后停止程序運行。

三 異常對象ex的使用

1 代碼

public class excepObject
{
  public static void main( String[] args )
  {
   try
   {
     int arr[] = new int[5];
     arr[10] = 7;
   }
   catch( ArrayIndexOutOfBoundsException ex )
   {
     System.out.println( "數(shù)組超出綁定范圍!" );
     System.out.println( "異常:" + ex ); // 顯示異常對象e的內(nèi)容
      // ex.printStackTrace();
   }
   System.out.println( "main()方法結束!" );
  }
}

2 運行

數(shù)組超出綁定范圍!
異常:java.lang.ArrayIndexOutOfBoundsException: 10
main()方法結束!

四 通過多個catch捕獲異常

1 代碼

public class arrayException {
  public static void main( String args[] ) {
    System.out.println("-----A、計算開始之前");
    try {
      int arr[] = new int[5];
      ;
      arr[0] = 3;
      arr[1] = 6;
      arr[1] = 0; // 除數(shù)為0,有異常
      arr[10] = 7; // 數(shù)組下標越界,有異常
      int result = arr[0] / arr[1];
      System.out.println("------B、除法計算結果:" + result);
    } catch (ArithmeticException ex) {
      ex.printStackTrace();
    } catch (ArrayIndexOutOfBoundsException ex) {
      ex.printStackTrace();
    } finally {
      System.out.println("-----此處不管是否出錯,都會執(zhí)行?。?!");
    }
    System.out.println("-----C、計算結束之后。");
  }
}

2 運行

-----A、計算開始之前
java.lang.ArrayIndexOutOfBoundsException: 10
    at arrayException.main(arrayException.java:19)
-----此處不管是否出錯,都會執(zhí)行?。?!
-----C、計算結束之后。

更多java相關內(nèi)容感興趣的讀者可查看本站專題:《Java面向對象程序設計入門與進階教程》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設計有所幫助。

相關文章

最新評論