视频学习地址
前言
通俗来说就是捕捉到错误,可以自定义异常并输出,最后关闭一些资源。
处理异常的五个关键字
- try:尝试
- catch:捕获
- finally:善后
- throw:方法体抛出异常
- throws:方法上抛出异常
public class Application {
public static void main(String[] args) {
try { //try监控区域
//System.out.println(1/0);
new Application().a();
}catch (Exception a){ //catch(想要捕获的异常类型)
System.out.println("程序出现异常,数字不能为0!");
}catch (Error a){
System.out.println("程序出现异常,栈溢出了!");
}catch (Throwable a){
System.out.println("程序出现异常!"); //最大的异常要在最下面,如果最大的在上面捕获了,就不会继续执行下面的异常了
}finally { //处理善后工作
System.out.println("finally");
}
//ctrl + alt + t是捕获异常快捷键
//假设要捕获多个异常,必须从上往下!
//可以不要finally,但是不能没有catch,finally在IO流里面,是用来关闭资源的
}
public void a(){
b();
}
public void b(){
a();
}
}
public class Application {
public static void main(String[] args) {
//用try catch依旧可以让程序正常运行,不至于结束程序
try {
new Application().test(1,0);
} catch (ArithmeticException e) { //捕获异常
System.out.println("Exception");
} finally { //处理善后
System.out.println("Finally");
}
}
//假设这个方法处理不了这个异常,那么在方法上抛出这个异常
public void test(int a,int b) throws ArithmeticException{
if (b == 0){ //能预料到的情况可以主动的抛出异常
throw new ArithmeticException(); //抛出的异常一般在方法中使用
}
//System.out.println(a/b); 没有做除法的操作
}
}