加载中...
第12章 异常
发表于:2021-06-15 | 分类: 《Java编程思想》读书笔记
字数统计: 328 | 阅读时长: 1分钟 | 阅读量:

异常类型:


12.4 创建自定义异常

创建自定义异常类并继承Throwable类或其子类

1
2
3
4
5
6
public class newException extends Exception{
public newException(){} //无参构造器 会自动产生最方便
public newException(String msg){
super(msg);
}
}

12.6 printStackTrace():

将打印“从方法调用处直到异常抛出处”的方法调用序列
printStackTrace()信息可由getStackTrace()直接访问

  • 返回一个栈数组,栈顶是最后一个调用的方法,栈底是第一个调用的方法

12.6.3 异常链

在捕获一个异常后抛出另一个异常,把原始异常信息保存起来,为异常链
异常链写法:

  1. 将catch到的异常对象作为cause参数放入构造器传递给下一个异常
  2. 创建异常对象实例化后用initCause(原始异常对象)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static void testOne() throws IOException{
throw new IOException("第一个异常");
}
public static void testTwo() throws Exception{
try {
testOne();
}catch (IOException e){
throw new IOException("第二个异常",e);
/* 写法二:
Exception e1 = new IOException("第二个异常");
e1.initCause(e);
throw e1;
*/
}
}
public static void main(String[] args) throws Exception {
try{
testTwo();
}catch (Exception e){
e.printStackTrace();
}
}

12.8 finally

除了System.exit(1)以外,其他任何情况都会执行finally,甚至跳过break,continue,return等语句。

上一篇:
第13章 字符串
下一篇:
第11章 集合
本文目录
本文目录