11.2 捕获异常

try{}catch(Throwable e){} 结构

执行过程:

(1)执行try 中的语句

(2) try中语句产生异常则不再执行 try 后续语句,执行 catch 中的语句

(3)try中语句没有异常则执行完 try 的所有语句, 不执行 catch 中的语句

如果不进行 try…catch 捕获,则必须使用 throws 向上抛出

11.2.1 捕获多个异常

写多个catch 对应不同异常即可

示例代码:

public class Main {
public static void main(String[] args) {
Main solution = new Main();
try {
int a = 2;
if(a==2)
throw new IOException("123");
solution.test(1/0);
} catch (FontFormatException e) {
System.out.println(ErrorUtil.getAllException(e));
}catch (ArithmeticException e){
System.out.println("ArithmeticException:"+ErrorUtil.getAllException(e));
}catch (Exception e){
System.out.println("Exception:"+ErrorUtil.getAllException(e));
}


}

private void test(int num) throws FontFormatException {
if(num==1)
throw new FontFormatException("test");
}
}

异常情况:

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_java

隐藏:

 if(a==2)

                throw new IOException("123");

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_抛出异常_02

特别注意,不能把Exception 放在 ArithmeticException 前面,父类必须放在后面,否则换一下Exception 和 ArithmeticException 位置,编译器会给出如下错误:

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_示例代码_03

11.2.2 再次抛出异常与异常链

在catch 块抛出新异常,使用 initCause 给出具体异常调用链

这里作者给的方法是 initCause, 这样写:

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_不执行_04

但是,其实可以这样写:

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_开发语言_05

完整代码:

public class Main {
public static void main(String[] args) throws Exception {
Main solution = new Main();
try {
int a = 2;
// if(a==2)
// throw new IOException("123");
solution.test(1/0);
} catch (FontFormatException e) {
System.out.println(ErrorUtil.getAllException(e));
}catch (ArithmeticException e){
System.out.println("ArithmeticException:"+ErrorUtil.getAllException(e));
Exception root = new RuntimeException("math check:", e);
throw new Exception(root);
}


}

private void test(int num) throws FontFormatException {
if(num==1)
throw new FontFormatException("test");
}
}

《Java 核心技术 卷1》 笔记 第11章 异常、日志、断言和调试(2)捕获异常与异常链_不执行_06

相关内容:选择 《Java核心技术 卷1》查找相关笔记

评论🌹点赞👍收藏✨关注👀,是送给作者最好的礼物,愿我们共同学习,一起进步

公众号 钰娘娘知识汇总