编译时异常又叫受检时异常,运行时异常又叫非受检时异常.开发中编译时异常可以用try-catch-finally处理将其转为运行时异常,对于运行时异常用throws比较好,抛出异常给上一级处理。
异常处理
- error:Java虚拟机无法解决的异常,如stackOverflowError.
- exception
try-catch-finally
,可以写多个catch异常,若多个异常之间存在关系,则子类异常在父类上面。
try{
int a = 10;
int b = 0;
System.out.println(a / b);
}catch (ArithmeticException e){
System.out.println("异常");
}finally {
System.out.println("finally");
}
//结果:异常 finally
try{
int a = 10;
int b = 0;
System.out.println(a / b);
return 1;
}catch (ArithmeticException e){
System.out.println("异常");
return 2;
}finally {
System.out.println("finally");
return 3;
}
int a = Test4();
System.out.println(a);
//结果: 异常 finally 3
throws
//如:
if(a > 0)
//dosomething;
else
throw new RuntimeException(); //运行时异常,编译时不报错
//throw new Exception(); 编译时报错
throw
手动抛出异常
子类重写的方法抛出的异常不大于父类异常- 自定义异常:让该类继承Exception / RuntimeException...
//example
class MyException extends Exception{
}