Java中捕獲和丟擲異常try/catch/finally
阿新 • • 發佈:2021-12-06
package com.exception; public class Test { public static void main(String[] args) { int a=1; int b=0; try{ new Test().a(); }catch (Error e){ System.out.println("死迴圈"); }finally { //finally作為善後工作必輸出 System.out.println("finally"); } System.out.println("=================="); //快捷鍵command+option+T try { System.out.println(a/b); } catch (Exception e) { System.out.println("程式出現異常,變數b不能為0"); } finally { System.out.println("finally"); } System.out.println("==================");try { new Test().b(); } catch (Exception e) { System.out.println("Exception"); } catch (Error e){ System.out.println("Error"); } catch (Throwable e){ System.out.println("Throwable"); //Throwable覆蓋面最大,要放最後 } finally { System.out.println("finally"); } } public void a(){ b(); } public void b(){ a(); } }
輸出:
死迴圈
finally
==================
程式出現異常,變數b不能為0
finally
==================
Error
finally
try/catch/finally快捷鍵生成:
Mac:command+option+T
Windows:ctrl+alt+T