Java——异常与捕获

几乎所有的代码里面都会出现异常,为了保证程序在出现异常之后可以正常执行完毕,就需要进行异常处理。

异常的继承类结构:

所有的异常都是由Throwable继承而来。

Error类:描述Java运行时内部错误与资源耗尽错误。这种内部错误一旦出现,除了告知用户并使程序安全终止之外,再无能为力。

Exception类(程序出错)

IOException:程序本身没问题,由于IO处理导致的程序出错

RuntimeException:由于程序错误导致的。

一、异常分为两大类:

1.非受查异常(无需强制处理):所有继承于Error或RuntimeException的异常类称为非受查异常

2.受查异常(需强制处理):所有继承于Exception与IOException的类称为受查异常

二、异常处理格式

try{

可能出现异常的语句

} [catch (异常类 对象)]{

出异常的操作

}[finally]{

异常出口

}

下面的格式都可以使用

try。。。catch。。。

try。。。finally。。。

try。。。catch。。。finally。。。

public class Test{
    public static void main(String[] args) {
        System.out.println("数学计算开始。。。");
        try {
            System.out.println("计算"+ 10 / 0);
        }catch (Exception e){
            System.out.println("分子不能为0");
            e.printStackTrace();
        }
        System.out.println("数学计算结束");
    }
}

无论是否产生异常,无论try catch是否有返回语句,最终都会执行finally块

打印错误堆栈:进行完整异常信息的输出。

e.printStackTrace();

三、throws关键字——作用于方法上

在进行方法定义时,如果要明确告诉调用者本方法可能产生哪些异常,可以使用throws方法进行声明,表示将异常抛回给调用方法。并且当方法出现问题后可以不进行处理。

public class Test{
    public static void main(String[] args){
        System.out.println("数学计算开始。。。");
        try {
            System.out.println("计算 " + fun(10, 0));
        }catch (Exception e){
            System.out.println("分子不能为0");
        }
        System.out.println("数学计算结束");
    }
    public static int fun(int a,int b)throws Exception{
        return a/b;
    }
}

在出现异常的fun方法中我没有进行处理,而是通过throws抛给了调用fun方法的方法中。这时就需要在主方法中进行处理。

这时主方法也可以通过throws将异常抛出,交给jvm处理。

四、throw关键字——用在方法中

thorw是直接编写在语句之中,表示人为进行异常的抛出。如果现在异常类对象实例化不希望由JVM产生而由用户产
生,就可以使用throw来完成

public class Test{
    public static void main(String[] args){
    try {
        throw new Exception("抛个异常");
    }catch (Exception e){
        e.printStackTrace();
    }
    }
}

结果

一般而言throw和break、continue、break都要和if结合使用。

五、自定义异常类

在Java里,针对于可能出现的公共的程序问题都会提供有相应的异常信息,但是很多时候这些异常信息往往不够我
们使用。如果我们有这样一个情况1+1不能等于2,那么程序中出现1+1=2就是一个异常。

我们可以自定义一个异常类来供我们使用,自定义异常类可以继承两种父类:Exception、RuntimeException。

class AddException extends Exception{
    public AddException(String msg){
        super(msg);
    }
}
public class Test{
    public static void main(String[] args) throws Exception{
        int a = 1;
        int b = 1;
        if(a + b == 2 ){
            throw new AddException("1 + 1 不能等于2");
        }
    }
}

六、Exception与RuntimeException的区别
1. Exception是RuntimeException的父类,使用Exception定义的异常都要求必须使用异常处理,而使用RuntimeException定义的异常可以由用户选择性的来进行异常处理。
2. 常见的RuntimeException:ClassCastException、NullPointerException等。

猜你喜欢

转载自blog.csdn.net/eve8888888/article/details/83512921