创建: 2020/11/19
完成: 2020/11/21
更新: 2020/12/13 修改标题[Java 错误处理] -> [Java 异常处理]
翻的时候脑子里想的异常处理,结果没找到😂别的语言里叫ensure的那个Java里叫啥记不清, 打finally文本没变粉,尴尬(可能拼错了)
| 语法 |
try {
...
} catch(ExceptionType1 param1) {
...
} catch(ExceptionType2 params) {
...
} finally {
...
}
- finally可省略, 相当于ruby的ensure
- catch也可省略, 至少要有一个catch或者finally
- 所有Exception类都继承Excepetion, 故default即为 catch(Excepation e) {...}
|
| 抛出异常 |
- object必须是java.lang.Throwable型
- 可以抛出时候生成
throws new ExceptionType(args);
|
| Throwable类 |
所有异常都继承Throwable
| 构造函数 |
| Throwable() |
|
| Throwable(String message) |
|
| Throwable(Throwable cause) |
|
| Throwable(String message, Throwable cause) |
|
|
| 实例方法 |
| String getMessage() |
|
| void printStackTrace() |
|
| Throwable getCause() |
|
|
| |
|
|
| Exception类 |
继承Throwable
| 构造函数 |
| Exception() |
|
| Exception(String message) |
|
| Exception(Throwable cause) |
|
| Exception(String message, Throwable cause) |
|
|
|
主要子类
java.lang
|
| ClassNotFountException |
|
| IllegalAccessException |
|
| InstantiationException |
实例抽象类或者实例 |
| InterruptedException |
|
| NoSuchFieldException |
|
| NoSuchMethodException |
|
| RuntimeException |
最常见
| 构造函数 |
| RuntimeException() |
|
| RuntimeException(String message) |
|
| RuntimeException(Throwable cause) |
|
| RuntimeException(String message, Throwable cause) |
|
|
| 子类 |
| ArithmeticException |
如/0等 |
| ArrayIndexOutFoBoundsException |
|
| ArrayStoreException |
|
| ClassCastException |
|
| IllegeArgumentException |
|
| NegativeArraySizeException |
|
| NullPointerException |
|
| SecurityException |
|
| TypeNotPresentException |
|
| UnsupportedOperationException |
|
|
|
| |
|
| |
|
|
|
java.io
|
IOException及其子类
|
|
| 声明可能抛出异常的函数 |
RuntimeException及其子类可以不声明
| 构造函数 |
consModifiers clsName(params) throws exceptions {
...
}
|
| 函数 |
mthModifiers rtype mthName(params) throws exceptions {
...
}
|
|
| 自定义异常 |
继承Exception类
|
| assert |
| |
assert expression;
assert expression:expression2;
- 必须返回true/false
- false时抛出AssertException
- expression2是字符串, 当条件为负以此初始化AssertException
|
| 开启assert |
运行时带上 -ea 或 -enableassertions
|
|
| |
|