天天看点

异常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();
        }
    }
}