异常处理机制
# 抛出异常
# 捕获异常
# 异常处理五个关键字
try,catch,finally,throw,throws
try-catch-finally
package demo01;
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // try 监控区域
System.out.println(a / b);
} catch (ClassCastException d) {
// 只能捕获对应的异常类型
System.out.println("ClassCastException");
} catch (ArithmeticException e) {
// catch(想要捕获的异常类型) 捕获异常,捕获对应的异常类型输出下面的语句
System.out.println("程序出现异常,变量b不能为0");
} catch (RuntimeException f) {
/*
catch 可以写多个,捕获多个异常
捕获的异常类型一般都范围大的异常写在下面。从小到大的去捕获
如果异常写在上面捕获了,就不会执行下面的捕获了
要有一种层层递进的感觉,不然写个 Throwable 什么异常都能捕获
下面也没必要再去写捕获异常了,当然这样写也会错
*/
System.out.println("RentimeException");
} finally {
/*
finally 处理善后工作,不论有没有异常都会执行,
如:之后学习 IO 流的时候需要关闭,关闭的时候可以放到 finally 里面一
finally 区域可以不要,try,catch 必须有
*/
System.out.println("finally");
}
/*
通过 catch 捕获异常后,可以让程序继续运行
*/
}
}
package demo01;
public class Test2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
/*
System.out.println(a/b);
快捷键,选中当前代码 Ctrl+Alt+T
*/
try {
System.out.println(a/b);
} catch (Exception e) {
throw new RuntimeException(e);
// 打印错误的栈信息
} finally {
}
}
}
throw-throws
package demo01;
public class Test3 {
public static void main(String[] args) {
int a = 1;
int b = 0;
if (b == 0) { // 主动抛出异常 throw
throw new ArithmeticException();
}
System.out.println(a/b);
}
}
package demo01;
public class Test3 {
public static void main(String[] args) {
try {
new Test3().test(1, 0);
} catch (ArithmeticException e) {
// 捕获下面抛出的异常
throw new RuntimeException(e);
} finally {
}
}
public void test(int a,int b) throws ArithmeticException {
if (b == 0) {
// 假设这个方法中,处理不了这个异常,可以在方法上抛出异常,throws
throw new ArithmeticException();
// 主动抛出异常一般在方法中使用
}
System.out.println(a / b);
}
}