java_基础_异常

之前只是了解的最基础的异常形式,没有过多的深入

今天因为一些原因了解了一下

下面来说说异常的几种形式

1.try-catch语句块

代码示例

class test{
    public static void main(String[] args) {
        try {
            int a = 1/0;
            System.out.println(a);
        }catch(ArithmeticException e) {
            e.printStackTrace();
            System.out.println(e);
        }finally{
//final语句块中最后都会执行(不管有没有异常)
    } } }

因为分母不能为零,所以此处会报出一个算术异常,这就是try-catch语句块基本形式了

2.抛出异常

代码示例:

class test{
    public static void main(String[] args) throws ArithmeticException{
            int a = 1/0;
            System.out.println(a);
    }
}

此处是将异常抛出了,通俗来讲,就是把异常丢给了上一级,由上一级来处理

3.语句中某种条件下抛出异常

代码示例:

class test{
    public static void main(String[] args) {
        try {
            int a = 1;
            int b = 0;
            if(b==0)throw new ArithmeticException("the denominator connot be zero");
            System.out.println(a);
        }catch(ArithmeticException e) {
            e.printStackTrace();
            System.out.println(e);
            System.out.println(e.getMessage());
        }
    }
}

此处,是在判断分母为零之后手动抛出的异常,这种异常可以自定义一句抛出的时候的语句,在catch语句中利用e.getMessage()方法可以获取自定义的语句,直接输出e对象,就是输出异常加上自定义语句,如上示例代码输出的是

java.lang.ArithmeticException: the denominator connot be zero
    at Excertion.Test.main(Test.java:12)
java.lang.ArithmeticException: the denominator connot be zero
the denominator connot be zero

这种方法更灵活

4.自定义异常

这种方法就是创建一个异常类,此类必须集成Exception父类,类中可以没有东西,也可以重写父类方法

示例代码:

class MyException extends Exception{
    private String message = "";
    
    MyException(String str){
        this.message+=str;
    }
    @Override
    public String getMessage() {
        // TODO 自动生成的方法存根
        return this.message;
    }
    
}

class test{
    public static void main(String[] args) {
        try {
            int a = 1;
            int b = 0;
            if(b==0)throw new MyException("the denominator connot be zero");
            System.out.println(a);
        }catch(MyException e) {
            System.out.println(e);
        }
    }
}

详细如上代码,此不再赘述

注:在try-catch语句块中错误出错代码或者手动抛出异常代码之后的语句不会被执行,但是在try-catch语句块之外之后的语句块会被执行

希望对大家有所帮助

以上

猜你喜欢

转载自www.cnblogs.com/lavender-pansy/p/10776391.html