1. 程式人生 > 其它 >基於ssm+vue的綜合專案 健康體檢管理系統-第八章

基於ssm+vue的綜合專案 健康體檢管理系統-第八章

  1. JVM預設的異常處理方式
  2. 開發中的異常處理方式

JVM預設的異常處理方式

定義:在控制檯列印錯誤資訊,並終止程式。

開發中的異常處理方式(兩種)

  • try...catch(finally):捕獲,自己處理
  • throws:丟擲,交給呼叫者

示例:

1.JVM預設的異常處理方式

public static void main(String[] args) {


        int a = 10/0;
        System.out.println(a);       
        System.out.println("結束!");
        
        
    }

執行結果:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at test.Tets01.main(Tets01.java:8)

2.1開發中的異常處理方式 try...catch(finally)

public static void main(String[] args) {

        
        try{
            
            int a = 10/0;
            System.out.println(a);
            
        }
        
catch(Exception e) { System.out.println("出現除以零的情況"); } finally { System.out.println("哈哈哈哈"); } System.out.println("結束!"); }

執行結果:

出現除以零的情況
哈哈哈哈
結束!

有無finally的區別:

public static void
main(String[] args) { try{ int a = 10/0; System.out.println(a); } catch(Exception e) { System.out.println("出現除以零的情況"); return;//跳出當前,結束該方法。 } finally { System.out.println("哈哈哈哈"); } System.out.println("結束!"); }

執行結果:

出現除以零的情況
哈哈哈哈

2.2開發中的異常處理方式 throws

丟擲異常交給呼叫者處理

兩種丟擲異常情況:

2.2.1呼叫者拿到異常,拋給上層

public static void main(String[] args) throws Exception{
    
    show();
}
public static void show() throws Exception { int a = 10/0; System.out.println(a); }

執行結果:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at test.Test02.show(Test02.java:21)
    at test.Test02.main(Test02.java:8)

2.2.2呼叫者自己處理

public static void main(String[] args){

        
        try {
            show();
        } catch (Exception e) {
            System.out.println("我在catch內。");
        }
        System.out.println("結束!");
        

    }
    
    public static void show() throws Exception
    {
        int a = 10/0;
        System.out.println(a);
        
    }

執行結果:

我在catch內。
結束!