淺析Java中的異常處理機(jī)制
異常處理機(jī)制
1、拋出異常
2、捕獲異常
3、異常處理五個關(guān)鍵字:
try、catch、finally、throw、throws
注意:假設(shè)要捕獲多個異常:需要按照層級關(guān)系(異常體系結(jié)構(gòu)) 從小到大!
package exception; /** * Java 捕獲和拋出異常: * 異常處理機(jī)制 * 1、拋出異常 * 2、捕獲異常 * 3、異常處理五個關(guān)鍵字 * try、catch、finally、throw、throws * 注意:假設(shè)要捕獲多個異常:需要按照層級關(guān)系(異常體系結(jié)構(gòu)) 從小到大! */ public class Test { public static void main(String[] args) { int a = 1; int b = 0; /** * try catch 是一個完整的機(jī)構(gòu)體,finally 可以不要 * 假設(shè)IO流,或者跟資源相關(guān)的東西,最后需要關(guān)閉,關(guān)閉的操作就放在 finally 中 */ try { //try 監(jiān)控區(qū)域 System.out.println(a / b); } catch (ArithmeticException exception){ //catch(想要捕獲的異常類型) 捕獲異常 System.out.println("程序出現(xiàn)異常,變量b不能為0"); } finally { //處理善后工作 System.out.println("finally"); } System.out.println("-------------- 分隔符 --------------"); try { new Test().a(); //無限循環(huán) } catch (Error error){ System.out.println("Error"); } catch (Exception exception){ System.out.println("Exception"); } catch (Throwable throwable){ System.out.println("Throwable"); } finally { System.out.println("finally"); } } public void a(){ b(); } public void b() { a(); } }
捕獲異常
快捷鍵:選中代碼 Ctrl + Alt + T
捕獲異常的好處:程序不會意外的停止,try catch 捕獲異常后程序會正常的往下執(zhí)行
package exception; /** * 捕獲異??旖萱I * 選中代碼后:Ctrl + Alt + T * 如: * 選中 System.out.println(a / b); * 然后快捷鍵 Ctrl + Alt + T */ public class Test2 { public static void main(String[] args) { int a = 1; int b = 0; try { System.out.println(a / b); } catch (Exception exception) { exception.printStackTrace(); //打印錯誤的棧信息 } finally { } } }
拋出異常
1、在方法中拋出異常:throw
2、在方法上拋出異常:throws
package exception; /** * 捕獲異常 * 拋出異常 */ public class Test3 { public static void main(String[] args) { /** * 方法中拋出異常 */ new Test3().test(1,0); //匿名內(nèi)部類直接調(diào)用 System.out.println("------------ 分隔符 -------------"); /** * 方法上拋出異常 * 捕獲異常的好處: * 程序不會意外的停止,try catch 捕獲異常后程序會正常的往下執(zhí)行 */ try { new Test3().test2(1,0); //匿名內(nèi)部類直接調(diào)用 } catch (ArithmeticException e) { e.printStackTrace(); } } /** * 在方法中拋出異常:throw * @param a * @param b */ public void test(int a, int b){ if (b == 0){ //throw throw new ArithmeticException(); //主動拋出異常,一般在方法中使用 } System.out.println(a / b); } /** * 假設(shè)在方法中處理不了這個異常,就在方法上拋出異常,然后捕獲異常 * 在方法上拋出異常:throws * @param a * @param b * @throws ArithmeticException */ public void test2(int a, int b) throws ArithmeticException{ if (b == 0){ throw new ArithmeticException(); } } }
以上就是淺析Java中的異常處理機(jī)制的詳細(xì)內(nèi)容,更多關(guān)于Java 異常處理機(jī)制的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Mybatis-Plus中的@TableName 和 table-prefix使用
table-prefix 是一個全局配置,它會自動在所有表名前添加指定的前綴,這個配置對于那些使用一致命名約定的數(shù)據(jù)庫表非常有用,這篇文章主要介紹了Mybatis-Plus中的@TableName 和 table-prefix使用,需要的朋友可以參考下2024-08-08SpringBoot JVM參數(shù)調(diào)優(yōu)方式
這篇文章主要介紹了SpringBoot JVM參數(shù)調(diào)優(yōu)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09SpringBoot前后端json數(shù)據(jù)交互的全過程記錄
現(xiàn)在大多數(shù)互聯(lián)網(wǎng)項目都是采用前后端分離的方式開發(fā),下面這篇文章主要給大家介紹了關(guān)于SpringBoot前后端json數(shù)據(jù)交互的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03