筆記:
/** 異常處理機制: 抓拋模型
* 1."拋", 一旦拋出,程序終止! printStackTrace()顯示異常路徑!
* 2."抓", 抓住異常
* try{
* //try語句聲明的變量是局部的,
* //可能出現異常的代碼
* }catch(Exception e1){
* //處理的方式1, 或者顯示提示信息
* }catch(Exception e2){
* //處理的方式2, 或者顯示提示信息
* }finally{
* //可選,可不選
* //無論如何,這個代碼是一定會執行的
* }
* 3.異常處理后,后面的代碼可以繼續執行!
* 4.在方法的聲明出, 顯式地拋出異常對象的類型
* -----------------------------------------
* 自定義異常處理
* 1.方法名() throws Class ExceptionList extends Exception
* 2.
* */
[筆記2]異常處理的5個關鍵字:
/**異常處理的5個關鍵字:
* 捕獲異常: try/catch/finally
* 拋出異常: throw 可以手動拋出異常對象;例如: throw new Exception("您輸入的數值存在負數!");
* 聲明異常: throws 聲明方法 可能要拋出的各種異常類,向上 傳遞異常,直到Main()函數!!:
* returnType methodName(....) throws ExceptionList{
* throw new ExceptionList("......");
* }
* class ExceptionList extends Exception{ //自定義的異常類
* }
代碼1:
public class TestExcption{ public static void main(String[] args) throws IOException { TestExcption.method1(); } static void method1() throws IOException ,FileNotFoundException{ FileInputStream fis =new FileInputStream(new File("hello.txt")); int ch; while((ch =fis.read())!=-1 ){ System.out.print((char)ch); } fis.close(); } }
運行1:
Exception in thread "main" java.io.FileNotFoundException: hello.txt (ϵͳÕҲ»µ½ָ¶) at java.base/java.io.FileInputStream.open0(Native Method) at java.base/java.io.FileInputStream.open(FileInputStream.java:219) at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157) at 任務138_處理異常.TestExcption.method1(TestExcption.java:35) at 任務138_處理異常.TestExcption.main(TestExcption.java:32)
代碼2:

import java.util.Scanner; public class EcmDef { public static void main(String[] args) { try{ Scanner cin=new Scanner(System.in); int i,j; i=cin.nextInt(); j=cin.nextInt(); EcmDef.ecm(i,j); }catch (NumberFormatException e){ System.out.println("異常:輸入數據類型不一致!"); }catch (ArrayIndexOutOfBoundsException e){ System.out.println("異常:缺少命令行參數"); }catch (ArithmeticException e){ System.out.println("異常:分母為0了"); }catch (EcDef e){ System.out.println(e.getMessage()); } } public static void ecm(int i,int j) throws EcDef{ //綜合應用throw()和throws()! if(i<0||j<0) throw new EcDef("您輸入的數值存在負數!"); else System.out.println(i/j); } } class EcDef extends Exception{ //自定義一個異常類, 兩個構造器直接 生成即可! public EcDef() { } public EcDef(String message) { super(message); } }
運行2:

1 -2 您輸入的數值存在負數! 1 0 異常:分母為0了