java異常處理的關鍵字有哪些?怎么用?這些問題可能是我們日常工作會見到的。通過這些問題,希望你能收獲更多。下面是揭開這些問題的詳細內容。
什么是異常?
異常有的是因為用戶錯誤引起,有的是程序錯誤引起的,還有其它一些是因為物理錯誤引起的。
異常處理關鍵字:
try、catch、finally、throw、throws
注意事項:
1、錯誤不是異常,而是脫離程序員控制的問題。
2、所有的異常類是從 java.lang.Exception 類繼承的子類。
3、異常類有兩個主要的子類:IOException 類和 RuntimeException 類。
4、Java有很多的內置異常類。
語法:
try{ //需要監聽的代碼塊 } catch(異常類型 異常名稱/e){ //對捕獲到try監聽到的出錯的代碼塊進行處理 throw 異常名稱/e; //thorw表示拋出異常 throw new 異常類型(“自定義”); } finally{ //finally塊里的語句不管異常是否出現,都會被執行 } 修飾符 返回值 方法名 () throws 異常類型{ //throws只是用來聲明異常,是否拋出由方法調用者決定 //代碼塊 }
示例代碼:(try與catch與finally)
public class ExceptionTest { public static void main(String[] args) { Scanner input=new Scanner(System.in); try{ //監聽代碼塊 int a=input.nextInt(); int b=input.nextInt(); double sum=a/b; System.out.println(sum); } catch(InputMismatchException e){ System.out.println("只能輸入數字"); } catch(ArithmeticException e){ System.out.println("分母不能為0"); } catch(Exception e){ //Exception是所有異常的父類 System.out.println("發生了其他異常"); } finally{ //不管是否出現異常,finally一定會被執行 System.out.println("程序結束"); } } }
示例代碼:(throw關鍵字)
import java.util.InputMismatchException; import java.util.Scanner; public class ExceptionTest { public static void main(String[] args) { Scanner input=new Scanner(System.in); try{ //監聽代碼塊 int a=input.nextInt(); int b=input.nextInt(); double sum=a/b; System.out.println(sum); } catch(InputMismatchException e){ //catch(異常類型 異常名稱) System.out.println("只能輸入數字"); throw e; //拋出catch捕捉到的異常 //throw new InputMismatchException(); 同上 } catch(ArithmeticException e){ System.out.println("分母不能為0"); throw new ArithmeticException("分母為0拋出異常"); //拋出ArithmeticException異常 } catch(Exception e){ //Exception是所有異常的父類 System.out.println("發生了其他異常"); } finally{ //不管是否出現異常,finally一定會被執行 System.out.println("程序結束"); } } }
示例代碼:(throws)
public class Throws { int a=1; int b=0; public void out() throws ArithmeticException{ //聲明可能要拋出的異常,可以有多個異常,逗號隔開 try{ //監聽代碼塊 int sum=a/b; System.out.println(sum); } catch(ArithmeticException e){ System.out.println("分母不能為0"); } finally{ //不管是否出現異常,finally一定會被執行 System.out.println("程序結束"); } } public static void main(String[] args){ Throws t=new Throws(); t.out(); //調用方法 throw new ArithmeticException("分母為0拋出異常"); //由調用的方法決定是否要拋出異常 /* * 第二種拋出方式 */ // ArithmeticException a=new ArithmeticException("分母為0拋出異常"); // throw a; } }
看完上述內容,你們對java異常處理的關鍵字以及使用方法大概了解了嗎?如果想了解更多相關文章內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。