java中异常

本文详细介绍了Java中的异常处理机制,包括异常与错误的区别、检查型异常与非检查型异常的分类,以及try、catch、finally等关键字的具体用法。特别强调了finally块的作用及其在程序流程控制中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类间继承图


1.分为异常与错误,而异常又分为检查型异常和非检查型异常。其中:RuntimeException均为非检查型异常,程序可正常编译。而非检查型异常无法通过编译。

2.异常关键字包括:try、catch、finally、throw、throws

①finally常用于回收在try中打开的物理资源(数据库、网络等)

finally中语句总是被执行,当finally中语句执行完后,再去执行try、catch中的return或throws语句;当finally中包含return或throws语句,则try或catch中的return或throws不再执行。

实例如下:

public class Test1 {

	private static int testFinallyFunc() {  
        String s = null;  
        int result;  
        try {  
            s.equals("ss");  
            result = 1;                             //不走  
            System.out.println("try " + result);    //不走  
        } catch (Exception e) {  
            result = 2;  
            System.out.println("catch " + result);  //走,且会给result赋值  
            return result;                          //不一定会return  
        } finally {  
            result = 3;  
            System.out.println("finally " + result);  
//            return result;                        //这个打开返回的就是finally中的结果 3;关闭返回的就是catch中的结果 2  
        }  
        return result;                              //这个就占个位置,打开finally的return这个返回就永远走不到了,得注释了。  
    }  
	
	private static int testFunc2() {  
	    int x = 1;  
	    try {  
	        return x;  
	    } catch (Exception e) {  
	        System.out.println(e.getMessage());  
	    } finally {  
	        ++x;  
	    }  
	    return x;  
	}  
  
    public static void main(String[] a) throws Exception {  
        int returnResult = testFinallyFunc();  
        System.out.println("get return result " + testFunc2());  
    }  

}

结论:

try、catch、finally都有返回:最终得到finally的返回结果。

try、catch有返回,finally无返回,try出现异常,会得到catch的返回结果。finally中的操作,不影响返回结果。

try、catch有返回,finally无返回,try未出现异常,会得到try的返回结果。finally中的操作,不影响返回结果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值