嵌套使用 trycatch,或者 trycatch 后面没有必要的 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/p/2670681.html