嵌套使用 try-catch,或者 try-catch 后面没有必要的 finally操作

分析

  数据库操作、IO 操作等需要使用结束 close()的对象必须在 try -catch-finally 的finally 中 close(),如果有多个 IO 对象需要 close(),需要分别对每个对象的 close()方法进行try-catch,防止一个 IO对象关闭失败其他 IO 对象都未关闭。


示例


  代码示例待补全。

  /**
     * 嵌套使用 try-catch,或者 try-catch 后面没有必要的 finally操作
     * 
     * @param filePath
     * @param strContent
     * @throws FileNotFoundException
     */
    public void writeFile(String filePath, String strContent)
            throws FileNotFoundException
    {
        PrintWriter printer = null;
        try
        {
            printer = new PrintWriter(new FileOutputStream(filePath));
            printer.print(strContent);

        }
        catch (IOException ex)
        {
            // 此处应记录日志
            ex.printStackTrace();
        }
        finally
        {
            printer.close();// 释放资源必须放在finally里面进行释放。

            // 若有多个资源需要释放应使用
            try
            {
                // 释放资源
            }
            catch (Exception e)
            { // TODO: handle exception
                // 记录日志
            }

            try
            {
                // 此处为非数据库,IO操作。纯粹的捕获异常。
            }
            catch (Exception e)
            { 
          // TODO: handle exception // 记录日志 } //无需添加finally } }

转载于:https://www.cnblogs.com/lltse/archive/2012/10/17/2670681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值