我有一个项目,其异常处理按以下方式编写:
父类拥有所有异常处理逻辑。被调用的类只是抛出异常,调用者类会用适当的逻辑进行处理。
现在我面临的问题是调用类打开不同的东西,例如文件。这些文件在异常发生时不会被关闭。
那么在这种情况下,异常处理的适当方法应该是什么。
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/