异常处理
1. 捕获异常
try - catch 结构
try - catch - finally 结构
格式:
try {
// 有可能出现异常代码
} catch (/* 对应处理的异常对象 */) {
// 处理方式
}
package com.qfedu.a_throwable;
public class Demo3 {
public static void main(String[] args) {
test(10, 2, null);
}
public static void test(int num1, int num2, int[] arr) {
int ret = 0;
try {
ret = num1 / num2;
System.out.println("测试代码");
arr[0] = 10;
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
System.out.println("ret:" + ret);
}
}
2. 抛出异常
throw
在方法内抛出异常
throws
在【方法声明】位置,告知调用者当前方法有哪些异常抛出
声明的异常需要生成对应的文档注释
package com.qfedu.a_throwable;
public class Demo4 {
public static void main(String[] args)
throws NullPointerException, ArithmeticException {
try {
test(10, 2, null);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
test(10, 0, null);
}
public static void test(int num1, int num2, int[] arr)
throws ArithmeticException, NullPointerException {
if (0 == num2) {
throw new ArithmeticException("算术异常");
}
if (null == arr) {
throw new NullPointerException("数组空指针异常");
}
System.out.println(num1 / num2);
arr[0] = 10;
}
}
3. 抛出和捕获的对比
捕获之后,代码可以正常运行,要保证处理之后的异常不会在导致其他问题。
例如:
用户名密码错误,不能采用捕获异常。
用户指定路径问题,也不能采用捕获异常。
抛出的确可以解决很多问题,并且可以让代码健壮性很强。到用户层面说什么都不能抛出异常。
所谓不能抛出,是指不能讲错误信息直接甩到用户脸上。
用户密码错误情况:
1. 捕获异常
2. 通过异常处理 catch将错误抛出
3. 给予用户的友好提示
4. 自定义异常
代码运行的过程中存在一定的生活化
例如:
用户名密码错误
NoGirlFriendException 自定义异常
自定义异常格式:
class 自定义异常类名 extends Exception {
// No Fields Constructor
// String Field Constructor
}
自定义异常类名:
必须Exception结尾!!!
```