javaException

异常

1、检查性异常:

2、运行时异常:

3、错误ERROR:

java.lang.Throwable是所有异常的超类。

异常处理的五个关键字

try、catch、finally、throw、throws

try{

}catch(想要捕获的数据类型){

}finally{

}

finally可以不要,try,catch必须有。

 try{//try监控区域

            new Twst().a();

            System.out.println(a/b);

            //捕获异常中要捕获多个异常,从小到大
        }catch(Exception e){       // catch(想要捕获的数据类型)
            System.out.println("Exception");
        }catch(Error z){
            System.out.println("catch");
        } catch (Throwable t){
            System.out.println("Throwable");
        }  finally
         {    //处理善后工作
            System.out.println("finally");
        }
//finally可以不要     需要关闭
    }

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

    //Ctrl+Alt+T
    try {
        System.out.println(a/b);
    } catch (Exception e) {
        System.exit(1254);//结束输出的错误名字
        e.printStackTrace();
    } finally {
    }
}
结果

Process finished with exit code 1254


public void text(int a,int b)throws ArithmeticException{
    if (b==0){//throw  throws
        throw new ArithmeticException();//主动抛出异常,一般用在方法中
    }
    System.out.println(a/b);
}

更上层的方法

public static void main(String[] args) {

    try {
        new Twst().text(1,0);
    } catch (ArithmeticException e) {
        System.out.println("11");
        e.printStackTrace();
    }

}

throw:主动抛出异常,一般用在方法中。

throws:如果这个方法中解决不了,向更上层的方法抛出。


自定义异常

自定义异常类 MyException

public class MyException extends Exception{
        //传递数字>10
    public int detail;

    public MyException(int a) {
        this.detail = a;
    }

    //to string:异常的打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

test类

public class Test {
    //可能会存在异常的方法
    static void test(int a) throws MyException {
        System.out.println("传递的参数为:" + a);
        if (a > 10) {
            throw new MyException(a);//抛出
        }
        System.out.println("ok");
    }

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

}
结果
传递的参数为:11
myexception-->MyException{detail=11}

posted @ 2021-09-23 14:11  星星淮  阅读(96)  评论(0)    收藏  举报