Throwable
异常Exception
非运行时错误(检查性错误)
运行时异常
- ArryIndexOutOfBoundsException 数组下标越界
- NullPointerException 空指针异常
- ArithmeticException 算术异常
- MissingResourceException 丢失异常
- ClassNotFoundException 找不到类
- 等等
Error
- 由JAVA虚拟机生成并抛出,大多数错误与程序员所执行的操作无关
- JVM运行错误(OutOfMemoryError)发生时,JVM会选择线程终止
error和exception的区别
Error:(与程序员无关)通常是灾难性的致命错误,是程序无法控制和处理的,当出现时,JVM一般会选择终止线程
Exception:(与程序员有关)通常情况下是可以被程序处理的且尽可能的去处理这些异常
异常处理机制
try
监控区域
catch
捕获异常;若要捕获多个异常:从小到大(eg.Throwable>Error、Exception)
catch(想要捕获的异常类型)
(以上两个必须要)ctrl+alt+t 快捷键
finally
处理善后工作(可以不要),无论执不执行 最后都会执行finally
public class Test {
public static void main(String[] args) {
int a = 1;
int b = 0;
try{ //try监控区域
System.out.println(a/b);
}catch(Error e){ //catch 捕获异常
System.out.println("Error!");
}catch (Exception e){
System.out.println("Exception!");
}catch(Throwable t){
System.out.println("Throwable!");
}finally { //处理善后工作
System.out.println("finally!");
}
}
}
throw
主动抛出异常,throw一般在方法里使用
public class Test02 {
public static void main(String[] args) {
new Test02().test(1,0);
}
public void test(int a,int b){
if(b==0){
throw new ArithmeticException();
//主动抛出异常,throw一般在方法中使用
}
}
}
throws
方法上抛出异常
public class Test02 {
public static void main(String[] args) {
try {
new Test02().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();
}
}
}
自定义异常
自己写一个异常类再继承Exception
总结
- 处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面,可以加一个catch(Exception)来处理可能漏掉的异常
- 对于不确定的代码,也可以加上try-catch处理潜在的异常
- 尽量去处理异常,切忌只是简单的调用用来打印输出
- 尽量添加finally语句块去释放占用的资源