RuntimeException(运行时异常):
ArrayIndexOutOfBoundsException(数组下标越界)
NullPointerException(空指针异常)
ArithmeticException(算术异常)
MissingResourceException(丢失资源)
ClassNotFoundException(找不到类)
可以看到报了算术异常 ArithmeticException,所以需要捕获异常
try 代码块里放需要执行的操作
catch 代码块里放出现异常后的措施
finally 代码块不管报不报异常都执行
try {
// try 监控区域
} catch (异常名 e) {
// catch 捕获异常
} finally {
//处理善后工作
}
public class Try {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { //try监控区域
System.out.println(a / b);
}catch (ArithmeticException e){ //catch捕获异常
System.out.println("执行异常,被除数不能为0");
}finally { //处理善后工作
System.out.println("finally");
}
}
}
运行结果:
快捷键:ctrl + alt + t
选择 try / catch / finally 也能直接生成捕获异常代码块
抛出异常:throw、throws(写的位置不一样)
主动抛出的异常,一般在方法中使用
throws 主要在方法上抛出异常
public class Try {
public static void main(String[] args) {
try {
new Try().test(1,0);
} catch (ArithmeticException e) {
throw new RuntimeException(e);
}
}
//假设这个方法中,处理不了这个异常,方法上抛出异常
public void test(int a,int b) throws ArithmeticException{
if(b == 0){
throw new ArithmeticException(); //主动抛出的异常,一般在方法中使用
}
}
}
注意自定义的方法不要写在 main 方法里
自定义异常,在类后面加 extends Exception
在多重 catch 块后面,可以加一个 catch(Exception) 来处理可能会被遗漏的异常
对于不确定的代码,也可以加上 try-catch,处理潜在的异常