Java:异常处理程序

标签 java exception

我有一个项目,其异常处理按以下方式编写:

父类拥有所有异常处理逻辑。被调用的类只是抛出异常,调用者类会用适当的逻辑进行处理。

现在我面临的问题是调用类打开不同的东西,例如文件。这些文件在异常发生时不会被关闭。

那么在这种情况下,异常处理的适当方法应该是什么。

    class A
    {
    private void createAdminClient()
    {

        try
        {
            B b = new B();          
                b.getClinetHandler();
        }
        catch(CustomException1 e1)
        {
        }   
        catch(CustomException2 e1)
        {
        }   
        catch(CustomException3 e1)
        {
        }
        catch(CustomException4 e1)
        {
        }
    }
}

class B
{
    ................
    ................

    getClinetHandler() throws Exception
    {
        --------------------------      
        ---- open a file----------
        --------------------------
        ----lines of code---------
        --------------------------      

        Exceptions can happen in these lines of code.
        And closing file may not be called      

        --------------------------      
        ---- close those files----
        --------------------------

    }

}

最佳答案

您可以将可能引发异常的代码包装在 try...finally block 中:

getClientHandler() throws Exception {
    // Declare things which need to be closed here, setting them to null
    try {
        // Open things and do stuff which may throw exception
    } finally {
        // If the closable things aren't null close them
    }
}

这样,异常仍然会冒泡到异常处理程序,但finally block 可确保在发生异常时仍然调用关闭代码。

关于Java:异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20500358/

相关文章:

java - 在 Spring 中创建对象池

java - 如何从集合中获取元素?

java - 如果每个异常捕获都应该记录它?

android - 从json中插入数据查询时出现sqlite异常?

java - 无效条目压缩大小

java - 如何解释这些时间戳?

java - 只需声明其总和和处理延迟即可从 args 读取输入文件

java - URL 的 Tomcat HTTP 500 错误

java - 为什么 SQLException 是已检查异常

java - 是否可以使用 try-with-resources 语句完全防止异常屏蔽