1,Java异常层次
图片:
Throwable 类有两个子类:Error 类和Exception类
Error(错误): 用来指示运行时环境发生的错误。例如,JVM 内存溢出。一般地,程序不会从错误中恢复。
Exception(异常):异常类有两个主要的子类:IOException 类和 RuntimeException 类。
2,捕获异常
Error 错误, 一般是指与虚拟机相关的问题,如系统崩溃、虚拟机错误、动态链接失败等,这种错误无法恢复或不可能
捕获,将导致应用程序中断, 通常应用程序无法处理这些错误,因此应用程序不应该试图使用 catch 块来捕获 Error 对
象,在定义该方法时,也无须在其 throws 子句中声明该方法可能抛出 Error 及其任何子类。
Exception异常:使用try和catch来捕捉异常,在try块中逻辑代码出现异常,系统会自动生成一个异常对象,异常对象
会交给Java运行环境,这个过程叫抛出异常(throw),当Java运行环境收到异常之后,会寻找处理该异常的catch块,
找到合适的catch块之后,会将异常交给catch块处理,这个过程叫 捕获异常,但是如果没有找到对应的catch块的话,运
行环境将会终止,Java程序也会退出。
try {
、、、、
}catch(ExceptionName e1) {
、、、、
}
异常捕获规则:先处理小异常,再处理大异常,因此,总是把对应 Exception 类的 catch 块放在最后,
public static void main(String[] args) {
try {
//略
}catch (IndexOutOfBoundsException ne){
System.out.println("数组越界:运行程序时输入的参数个数不够");
}catch (NumberFormatException ne){
System.out.println("数据格式异常");
}catch (NullPointerException ne){
System.out.println("空指针异常");
}catch(Exception e){
System.out.println("未知异常");
}
}
} catch (Exception e) {
log.error("系统错误!" + e.getMessage(), e);
}
3,finally关键字
无论是否发生异常,finally 代码块中的代码总会被执行。
在 finally 代码块中,可以运行清理类型等收尾善后性质的语句,回收资源。
try必须出现, catch, finally 块二选一
public static void main(String[] args) {
try {
int i=1;
i=i/0;
}catch(Exception e){
System.out.println("未知异常");
return;
}finally{
System.out.println("结束。。");
}
}
public static void main(String[] args) {
try {
int i=1;
i=i/0;
}catch(Exception e){
System.out.println("未知异常");
// return;
System.exit(1);//退出虚拟机
}finally{
System.out.println("结束。。");
}
}
****结论:
除非在try块和catch块中调用了退出虚拟机的方法,否则,不管try块和catch块中执行了什么代码,出现什么样的
情况,finally块中的语句都会被执行
public static void main(String[] args) {
boolean bool=restr();
System.out.println(bool);
}
public static boolean restr(){
try {
return true;
}catch(Exception e){
return true;
}finally{
return false;
}
}
}
public static boolean restr(){
try {
System.out.println("try1");//1
return true;
}catch(Exception e){
System.out.println("catch");
return true;
}finally{
System.out.println("finally");//2
return false;//3
}
}
*结论:
*一旦finally块中使用了return 和throw语句,将会导致try,catch块中的return 和throw语句失效
4,throw和throws关键字
public static void main(String[] args) throws Exception{
int i=1/0;
System.out.println("Exception");
}
public static void main(String[] args) throws Exception{
int i=1/0;
throw new ArithmeticException();
}
public static void main(String[] args) throws Exception{
int i=1/0;
// throw new ArithmeticException();
try{
System.out.println("111");
}catch (Exception e){
}
}
throw是由自行抛出异常,throws将异常交给JVM处理
throw与throws的区别
1、throw用在方法体内,上面代码显示了,是直接在main方法体内
throws用在方法声明后面,表示再抛出异常,由该方法的调用者来处理。这个看上面的代码就理解了。
2、throw是具体向外抛异常的,抛出的是一个异常实例。
throws声明了是哪种类型的异常,使它的调用者可以捕获这个异常。
3、throw,如果执行了,那么一定是抛出了某种异常了,throws表示可能出现,但不一定。
4、同时出现的时候,throws出现在函数头、throw出现在函数体,两种不会由函数去处理,真正的处理由函数的上层调用处理。