淺析Java中的異常處理機制
異常處理機制
1、拋出異常
2、捕獲異常
3、異常處理五個關鍵字:
try、catch、finally、throw、throws
注意:假設要捕獲多個異常:需要按照層級關系(異常體系結構) 從小到大!
package exception;/** * Java 捕獲和拋出異常: * 異常處理機制 * 1、拋出異常 * 2、捕獲異常 * 3、異常處理五個關鍵字 * try、catch、finally、throw、throws * 注意:假設要捕獲多個異常:需要按照層級關系(異常體系結構) 從小到大! */public class Test { public static void main(String[] args) { int a = 1; int b = 0; /** * try catch 是一個完整的機構體,finally 可以不要 * 假設IO流,或者跟資源相關的東西,最后需要關閉,關閉的操作就放在 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); } /** * 假設在方法中處理不了這個異常,就在方法上拋出異常,然后捕獲異常 * 在方法上拋出異常:throws * @param a * @param b * @throws ArithmeticException */ public void test2(int a, int b) throws ArithmeticException{ if (b == 0){ throw new ArithmeticException(); } }}
以上就是淺析Java中的異常處理機制的詳細內(nèi)容,更多關于Java 異常處理機制的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. 使用Python webdriver圖書館搶座自動預約的正確方法2. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題3. Python sublime安裝及配置過程詳解4. Linux刪除系統(tǒng)自帶版本Python過程詳解5. Python 合并拼接字符串的方法6. Python3 json模塊之編碼解碼方法講解7. python 使用事件對象asyncio.Event來同步協(xié)程的操作8. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條9. Java Long類型對比分析10. ASP基礎知識VBScript基本元素講解

網(wǎng)公網(wǎng)安備