异常

异常

  • 异常的出现会导致程序崩溃,如果使用异常处理机制可以保证程序能正常的执行下去

  • Java把异常当做对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类

  • Throwable分为Error和Exception两大类

  • Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关

  • Exception一般是由程序逻辑错误引起的

  • 异常处理机制包括抛出异常和捕获异常

  • 异常处理关键字:try、catch、finally、throw和throws


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

        try {            // try监控区域   Ctrl + Alt + T
  
            System.out.println(a/b);

        }catch (Error e){//捕获异常

            System.out.println("出现了错误");

        }catch (Exception e)//包含范围越大的越往后写,Exception和Error无大小之分,
                            //叠加catch中只会生效一个
        {
            System.out.println("出现了异常");
        }

        finally
         {                  //不管有没有异常都会执行finally,多用来进行IO资源的关闭,
                            // finally可以没有,try-catch必须要有
        }

    }

}

public class TestException {
    public static void main(String[] args) {
           try {
            new TestException().test(1,0);
        } catch (Exception e) {
            System.out.println("抓到你了");
        } 

}
    public void test(int a,int b){    
        if (b==0)
        {
            throw new ArithmeticException();//主动抛出异常 throw:一般在方法中使用,不执行后面的“======”
        }
        System.out.println("================");//不执行
        System.out.println(a/b);
    }
}

public class TestException {
    public static void main(String[] args) {
        try {
            new TestException().test(1,0);
        } catch (Exception e) {
            System.out.println("抓到你了");
        } 
    }
                      //假设方法中处理不了这个异常,就在方法上抛出异常throws
    public void test(int a,int b) throws ArithmeticException{  
        System.out.println(a/b);
    }
}

  • 用户自定义异常类只需要继承Exception
Test.java
public class Test {

    static void test(int a) throws MyException {
        if (a>5){
            throw new MyException(a);
        }
        System.out.println("没问题");
    }

    public static void main(String[] args) {
        try {
            test(7);
        } catch (MyException e) {
            System.out.println("哎呦,您来啦"+e);
        } finally {
        }
    }
}
MyException.java        //自定义异常类
public class MyException extends Exception {

    private int a=10;

    public MyException( int a){  //有参构造
        this.a = a;
    }

    @Override    // e
    public String toString() {
        return "MyException{" +
                "a=" + a +
                '}';
    }
}

posted @ 2021-06-12 13:23  bobochen  阅读(51)  评论(0)    收藏  举报