web-异常

266 阅读2分钟

原理和机制

1.捕获异常

为什么要捕获异常?

处理异常

比如
记录日志

捕获的是谁的异常?

当前API捕获的
永远是下级的API抛出来的异常

一个异常会被捕获几次?

只会被捕获一次
而且永远是下级API出现异常,但是下级API没有捕获,而是向上抛,这个时候上级API就捕获了下级API的异常

具体是怎么捕获异常的?

下级API出现异常
但是下级API没有捕获
而是向上抛
这个时候上级API就捕获了下级API的异常

2.抛出异常

向上抛异常

3.如何抛异常

1.方法声明 抛异常

public void 方法名字 throws Exception{

}

2.捕获代码里 抛异常

try{

}catch(Exception e){
记录日志;

throw new Excetion(e);

}

代码

package exception;

public class TestException {

	public static void main(String[] args) {
		try {
			call1();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		int i = 1;
	}

	private static void call1() throws Exception{
		try {
			call3();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		int i = 1;
	}

	private static void call3() throws Exception{
		call4();
	}

	private static void call4() throws Exception{
		try {
			int i = 1/0;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		}
		
		int j = 1;
	}

	private static void call2() throws Exception{
		try {
			int i = 1/0;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		int j = 1;
	}

}

输出日志

java.lang.ArithmeticException: / by zero
	at exception.TestException.call4(TestException.java:31)
	at exception.TestException.call3(TestException.java:26)
	at exception.TestException.call1(TestException.java:17)
	at exception.TestException.main(TestException.java:7)
java.lang.Exception: java.lang.ArithmeticException: / by zero
	at exception.TestException.call4(TestException.java:34)
	at exception.TestException.call3(TestException.java:26)
	at exception.TestException.call1(TestException.java:17)
	at exception.TestException.main(TestException.java:7)
Caused by: java.lang.ArithmeticException: / by zero
	at exception.TestException.call4(TestException.java:31)
	... 3 more

异常类

1.异常要分的很细

2.之所以分的那么细
是为了根据异常类的类名,就能一眼看出来是什么类型的错误

3.最后
再看具体是哪一行代码报错,即栈跟踪

疑问

1.问题描述 业务层为什么没有捕获底层DAO框架抛的异常,而是被控制器捕获了异常?

再现异常的步骤

1)控制器捕获异常
捕获异常
打印日志

2)业务类方法抛出异常,捕获异常
报错 没有捕获异常 //业务层为什么没有捕获底层DAO框架抛的异常,而是被控制器捕获了异常?

3)DAO没有抛出异常,没有捕获异常

4)底层DAO框架
捕获异常
打印日志

2.原因分析

3.解决方法

参考

https://www.zhihu.com/question/28254987