天天看點

異常Exception(Java)

Exception(Java)

public class Demo01 {
    public static void main(String[] args) {
    // System.out.println(11/0); //報錯
        new Demo01().a(); //出現異常  a調b  b調a 無限循環下去
    }
    public void a(){
        b();
    }
    public  void b(){
        a();
    }
}      
public class Test01 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
            
        }


    }
   /* public void a(){
        b();
    }
    public  void b(){
        a();
    }*/

    //假設這方法中,處理不了這個異常,我們可以在方法上抛出(throws)
    public void test(int a,int b) throws ArithmeticException{
        if(b==0) //主動抛出異常 throw throws
        {
            throw new ArithmeticException();//主動抛出一個異常 ,一般在方法中使用

        }
        System.out.println(a/b);

    }

}

/*
        //假設要捕獲多個異常,需從小到大!Error<Exception<Throwable
       try {  //try 監控區域
          System.out.println(a/b);
         //  new Test().a();
        }catch(Error e)//catch(想要捕獲的異常類型) 捕獲異常//若上邊出現異常,則執行下邊
       {
          // System.out.println("程式出現異常");

           System.out.println("Error");
       }catch (Exception e){
           System.out.println("Exception");

       }catch (Throwable e){
           System.out.println("Throwable");

       } finally {//處理善後工作
           System.out.println("finally");
       }
       //finall 可以不要finally       假設IO 資源  ,關閉!
*/      
public class Test02 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            System.exit(2);  //出現異常 退出
            e.printStackTrace(); //列印錯誤的資訊
        } finally {
        }
    }
}      
//繼承extends Exception類後 變為自定義異常
public class MyException extends Exception{
    //傳遞數字,當大于10的時候抛出異常
    private int detail;
      MyException(int a)
    {
        this.detail=a;
    }

    //toString:異常的列印資訊
    @Override
    public String toString() {
       return "MyException{"+
                "detail=" + detail+
                '}';
    }
}      
public class Test {
    //可能會存在異常的方法
    static void test(int a) throws MyException {
        System.out.println("傳遞的參數為:"+a);
        if(a>10){
            //這裡抛出異常,也可以捕獲異常
                throw new MyException(a);  //這裡選擇抛出異常throws MyException
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            System.out.println("MyException=>"+e);
           //  e.printStackTrace();
        }
    }
}