什么时候用 throws Exception ?
1、在尝试封装自己的工具类的时候,发现有一些异常try-catch后毫无意义,所以这时候,就需要throws,抛到一个合理的位置,执行合理的处理方法
2、一般在写程序的时候 dao层、service层的异常 无论是系统一样还是程序员自定义的异常,都会向上抛出,即throws,在控制层Controller 做异常捕捉处理。
看到一段代码 方法 try...catch了 方法后还写了throws Exception 有什么作用?
catch是这段代码捕获了异常,可以做相应的处理。这时候根据需要是不是throws给调用类,因为有可能在调用的上级类里面也需要对异常做相应的处理。这个时候throws的类就可以被调用方的catch捕获。
demo1
复制收展Javapackage com.com.test;
/**
* @Desc
* throws Exception 表示的是本方法不处理异常,交给被调用处处理。
* 当方法无法处理抛出的异常的时候 可以通过throws把异常抛给方法的上一级调用者,如果上一级调用者还是无法处理,继续可以向上抛,直到抛给jvm处理(jvm的默认处理就是打印错误堆栈信息)
* @Author luolei
* @Date 2021/10/08 17:42
* 输出:
* 主方法捕获异常
*/
public class ThrowsException {
public static void main(String[] args) {
try {
new ThrowsException().method1();
} catch (Exception e) {
System.out.println("主方法捕获异常");
}
}
public void method1() throws Exception{
method2();
}
public void method2() throws Exception {
method3();
}
public void method3() throws Exception{
throw new Exception("人为的抛出一个异常!");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
demo2
复制收展Javapackage com.com.test;
/**
* @Desc
* @Author luolei
* @Date 2021/10/08 17:42
* 输出:
* 出错了
*/
public class ThrowsException2 {
public static void main(String[] args) {
try {
new ThrowsException2().method1();
}catch (Exception e){
System.out.println("主方法捕获异常");
}
}
public void method1(){
method2();
}
public void method2() {
method3();
}
public void method3(){
try {
throw new Exception("人为的抛出一个异常!");
}catch (Exception e){
System.out.println("出错了");
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37