JAVA的异常体系
1、所有的异常体系均继承于Throwable
2、异常分为检查异常(checkedException)与非检查异常(unCheckedException)
3、检查异常(除了Error与RuntimeException)
4、非检查异常(错误Error与运行时异常RuntimeException)
处理异常
抛出异常
手动抛出
public void exceptionDemo throws ArithmeticException (){
throw new ArithmeticException();
}
自动抛出
/**
* 什么是自动抛出,即未对异常进行任何处理(包含未手动抛出),由JVM对其进行判断和抛出
*
* 此demo 抛出的异常为ArithmeticException();
*/
public Integer exceptionDemo(){
return 1/0;
}
捕获异常
public Integer exceptionDemo1(int a, int b){
try{
return a/b;
}catch(Exception e){
System.out.println("抓住异常一枚");
e.printStackTrace();
}
}
public Integer exceptionDemo2(int a, int b){
try{
return a/b;
}catch(ArithmeticException e){
System.out.println("抓住除0异常一枚");
e.printStackTrace();
}catch(Exception e){
System.out.println("抓住异常一枚");
e.printStackTrace();
}
}
注意:异常可以向switch一样,进行多重捕获, 但是Exception建议放在最后一个,避免无法得到有效的信息。
catch中的异常应按照最小---->最大进行排序。
如何自定义异常
核心:所有的自定义异常均应继承于Exception
public class SimpleException extends Exception {
public SimpleException(){
super();
};
public SimpleException(String message){
super(message);
}
}
一个简单的异常就这样创建完成啦。