(一)異常的概念數組
異常是指程序在編譯或運行時出現的致使程序不能繼續編譯或運行的情況。、spa
(二)Throwable類線程
Throwable類繼承自Object類,是Java中全部錯誤或異常的超類,只有該類及其子類的對象才能經過throw語句拋出。Throwable類的子類有Error類和Exception類。指針
在異常機制中,編譯時的異常直接繼承自Exception類,而運行時異常繼承自其子類RuntimeException類。code
(三)異常的處理orm
異常的處理是經過try/catch語句進行捕獲並處理。對象
①try語法:try{ [可能出現異常的代碼] };blog
②catch語法:catch ( [預匹配的異常] ) { [處理代碼] };繼承
示例:ci
Scanner input = new Scanner(System.in);
try { System.out.println("請輸入被除數"); int n1 = input.nextInt(); System.out.println("請輸入除數"); int n2 = input.nextInt(); System.out.println("結果爲:"+n1/n2); } catch (ArithmeticException e) { System.out.println("分母不能爲0"); System.out.println(e.getMessage()); e.printStackTrace(); }catch (InputMismatchException e) { System.out.println("分子分母都應該是數字"); System.out.println(e.getMessage()); }catch (Exception e) { System.out.println("出現了未知異常"); } //捕獲多個異常分別處理
Scanner input = new Scanner(System.in); try { int n = input.nextInt(); } catch (InputMismatchException | ArithmeticException |ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } //捕獲多個異常合併處理
(注:在多重catch機制中,try模塊發生異常時,異常機制按catch順序逐個匹配異常,一旦匹配成功則再也不繼續匹配)
(四)finally關鍵字
不管方法在執行過程當中是否發生異常,方法中的finally模塊都會執行。
Scanner input = new Scanner(System.in); try { int n = input.nextInt(); } catch (InputMismatchException e) { e.printStackTrace(); } finally { System.out.println("finally"); }
(注:finally必須與try或try/catch配合使用;在方法執行return語句前,未執行的finally模塊將被強制執行)
(五)異常對象的經常使用方法
①printStackTrace():打印輸出異常的堆棧信息;
②getMessage():返回異常信息描述字符串。
(六)常見的異常
異 常 |
描 述 |
Exception |
異常層次結構的父類 |
NullPointerException |
空指針異常 |
ClassNotFoundException |
類不存在 |
ClassCastException |
對象強制類型轉換出錯 |
ArithmeticException |
算術錯誤 |
ArrayIndexOutOfBoundsException |
數組下標越界 |
IllegalArgumentException |
方法參數異常 |
NumberFormatException |
數字格式轉換異常 |
(七)throws關鍵字
throws關鍵字用於聲明異常,將該方法出現的異常反饋給上層方法處理。
InterruptedException { try { test(); } catch (IOException e) { e.printStackTrace(); }
} static public void test() throws InterruptedException,IOException{ System.out.println("線程休眠開始"); Thread.sleep(2000); System.out.println("線程休眠結束"); }
(注:main方法聲明的異常由JVM處理)
(八)throw關鍵字
throw關鍵字用於拋出異常,使程序進入異常處理機制。
if (!("男".equals(gender) || "女".equals(gender))) { Exception exp = new Exception("性別只能是男或女"); throw exp; }
(九)自定義異常
自定義異常是經過繼承異常的類而建立了該異常類的子類,主要用於精確地捕獲指定異常。
public class AgeException extends Exception{
public AgeException() { super(); } public AgeException(String msg) { super(msg); } }
———————————————————————————————————————————————————————————————————
The end @ 萬有引力+
-
-
-
-
-