关于在catch中抛异常
来源:2-5 初始化工具类MyBatisUtils
qq_苍麋_wIMVY1
2019-11-13 21:17:54
为什么之前写代码的时候在捕捉到异常以后直接在catch块中打印出异常。
而现在却又在catch块中再次抛出?抛出的目的为了什么?
老师能详细解释一下吗。
1回答
同学你好。异常我们是需要对其做处理的,最简单粗暴的处理方式,就是将异常捕获然后打印一下堆栈信息。但异常被捕获后,外界就感受不到这个异常了。
public class Test {
public static void main(String[] args) {
try {
new throwTest().b();
System.out.println("a感受不到异常");
} catch (Exception e) {
System.out.println("a感受到了异常,异常信息为:");
System.out.println(e.getMessage());
//这里a有权做一些处理后在终止程序
System.out.println("这里a有权做一些处理后在终止程序");
}
}
}
class throwTest{
public void b() throws Exception{
try {
throw new Exception("b中发生了异常");
} catch (Exception e) {
e.printStackTrace();
System.out.println("没有抛出异常");
//throw e;
}
}
}为了外界能捕获到这个异常信息,而不是直接终止运行程序,我们需要将异常抛出。
public class Test {
public static void main(String[] args) {
try {
new throwTest().b();
System.out.println("a感受不到异常");
} catch (Exception e) {
System.out.println("a感受到了异常,异常信息为:");
System.out.println(e.getMessage());
//这里a有权做一些处理后在终止程序
System.out.println("这里a有权做一些处理后在终止程序");
}
}
}
class throwTest{
public void b() throws Exception{
try {
throw new Exception("b中发生了异常");
} catch (Exception e) {
e.printStackTrace();
System.out.println("抛出异常");
throw e;
}
}
}如果解答了同学的疑问,望采纳~
祝学习愉快~
相似问题