Java異常(2)- 捕獲和拋出異常


異常處理五個關鍵字:try,catch,finally,throw,throws

 

捕獲異常

try、catch、finally

package oop.demo10;

public class Outer {
    public static void main(String[] args) {
        int a = 1;
        int b =0;

        //捕獲多個異常:范圍從小到大
        try {//try監控區域
            System.out.println(a/b);
        } catch (Error e) {//catch(想要捕獲的異常類型)捕獲異常
            System.out.println("Error");
        } catch (Exception e) {
            System.out.println("Exception");
        }catch (Throwable e) {
            System.out.println("Throwable");
        }finally {//處理善后工作
            System.out.println("finally");
        }
    }
}

選中代碼:Ctrl+Alt+T快捷鍵

拋出異常

throw:一般用於方法中拋出異常

throws:在方法上拋出異常

package oop.demo10;

public class Outer {
    public static void main(String[] args) {
        new Outer().test(1,0);
    }

    //假設方法中,處理不了這個異常。那就通過throws在方法上拋出異常
    public void test(int a,int b) throws ArithmeticException{
        if (b==0){
            throw new ArithmeticException();//throw 主動拋出異常
        }else{
            System.out.println(a/b);
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM