【Java】Exception异常类的基础知识
1.Java的异常处理模型有3类:
- 声明异常
- 抛出异常
- 捕获异常
2.异常有两种:
免检异常
必检异常
3.如果父类方法没有声明异常,那么,在子类中不能对其进行覆盖以声明;
4.异常处理的逻辑:
先从当前方法,调用链向后寻找,如果找到,则将该异常对象赋值给所声明的变量,执行catch块中的代码,所以,catch的代码块中的异常类的顺序很重要;先小后大,先子后父的顺序为佳;如果没有,则退出该方法,到调用该方法的方法内继续寻找相应的处理代码块(也叫处理器),以此类推,如果都没有,则程序终止,并在控制台打印错误信息;
5.一个父类可以派生出多种异常类,如果一个catch块可以捕获一个父类异常,那它就可以捕获该父类的所有子异常;
6.我们来看一个具体的例子:
这里是一个带有异常的圆类,如果输入半径为负数,则抛出异常;
public class CircleWithException {
private double radius;
private static int numberOfObjects = 0;
public CircleWithException(){
this(1.0);
}
public CircleWithException(double newRadius){
setRadius(newRadius);
numberOfObjects++;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
if (radius>=0){
this.radius = radius;
}else{
throw new IllegalArgumentException("输入值小于0!");
}
}
public static int getNumberOfObjects() {
return numberOfObjects;
}
public static void setNumberOfObjects(int numberOfObjects) {
CircleWithException.numberOfObjects = numberOfObjects;
}
public double findArea(){
return radius * radius * Math.PI;
}
}
测试类
public class TestCircleWithException {
public static void main(String[] args) throws Exception {
try {
CircleWithException c1 = new CircleWithException(5);
System.out.println(c1.findArea());
CircleWithException c2 = new CircleWithException(-5);
System.out.println(c2.findArea());
CircleWithException c3 = new CircleWithException(0);
System.out.println(c3.findArea());
} catch (Exception e) {
//e.printStackTrace();
//System.out.println(e);
//throw new Exception();
}
System.out.println("对象创建个数:"+CircleWithException.getNumberOfObjects());
}
}
测试结果1:对捕获的异常不做任何处理;
如果不做任何处理,try-catch块内出现异常,将不影响try-catch外的代码运行,但是你也不知道try-catch内代码执行情况,即不知道监测代码块是否出现了异常;
测试结果2:打印报错信息;
不影响try-catch代码块之外的代码运行情况,但是会在结束后打印try-catch代码块里的报错信息;
测试结果3:控制台打印报错信息;
控制台打印报错信息;
测试结果4:抛出异常
监控代码块出现问题,抛出异常,并且不会执行try-catch代码块之外的代码;该线程终止;
7.链式异常:
如果方法间有调用关系,底层方法出现异常,抛到上层方法,在上层方法打印,那么链式异常可以将上层异常和底层异常一起打印出来;请看下面的例子:
public class ChainedExceptionDemo {
public static void main(String[] args) {
try {
method1();
}catch (Exception e){
e.printStackTrace();
}
}
public static void method1() throws Exception{
try {
method2();
}catch (Exception e){
throw new Exception("method1异常",e);
}
}
public static void method2() throws Exception{
throw new Exception("method2异常");
}
}
测试结果如下图: