Java:异常处理程序
我有一个项目使用以下方式编写异常处理: 父类具有所有异常处理逻辑。被调用的类只是抛出异常,调用器类用适当的逻辑进行处理 现在我面临的问题是调用类打开不同的东西,例如,一个文件。这些文件在发生异常时不会关闭 那么,在这种情况下,什么是适当的异常处理方式呢Java:异常处理程序,java,exception,exception-handling,Java,Exception,Exception Handling,我有一个项目使用以下方式编写异常处理: 父类具有所有异常处理逻辑。被调用的类只是抛出异常,调用器类用适当的逻辑进行处理 现在我面临的问题是调用类打开不同的东西,例如,一个文件。这些文件在发生异常时不会关闭 那么,在这种情况下,什么是适当的异常处理方式呢 class A { private void createAdminClient() { try { B b = new B();
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----
--------------------------
}
}
使用
finally
块完成最终任务。比如说
try
{
B b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1)
{
}
finally{
// close files
}
从
当try块退出时,finally块始终执行。这确保即使发生意外异常,也会执行finally块。但最后,它不仅仅适用于异常处理——它允许程序员避免因返回、继续或中断而意外绕过清理代码。将清理代码放在finally块中始终是一种好的做法,即使在没有预期异常的情况下也是如此
我就是这样做的
try {
//What to try
} catch (Exception e){
//Catch it
} finally {
//Do finally after you catch exception
try {
writer.close(); //<--Close file
} catch (Exception EX3) {}
}
试试看{
//试一试
}捕获(例外e){
//抓住它
}最后{
//在捕捉到异常后,是否最终执行此操作
试一试{
writer.close();//使用块来处理后处理执行(无论它成功还是失败)。如下所示:
// Note: as Sean pointed out, the b variable is not visible to the finally if it
// is declared within the try block, therefore it will be set up before we enter
// the block.
B b = null;
try {
b = new B();
b.getClinetHandler();
}
catch(CustomException1 e1) {
} // and other catch blocks as necessary...
finally{
if(b != null)
b.closeFiles() // close files here
}
始终执行finally
块,不管如何,即使您从try
或catch
块中抛出或返回
提供了一个非常好的解释,说明了finally
块在这种情况下如何工作,以及何时/如何执行,基本上进一步说明了我刚才写的内容。您可以包装可能在try…finally块中引发异常的代码:
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块确保在发生异常时仍会调用关闭代码。这不是他们想要的。可关闭的对象在此代码块中不可见。@Sean我认为这是他们想要的,因为他们最终会问如何在e之后关闭文件执行(在getClientHandler
方法中)但是您确实指出了一个缺陷,即b
变量不可见,我将对此进行更正。Hi Teeg,我粘贴的代码段,基本上父类具有所有异常处理逻辑。如果我在这种情况下选择这种方式,closeFiles和其他处理可关闭对象的处理逻辑必须转到父类-我不想这样。@baishak啊,好吧,这很合理。肖恩的回答是在这方面有更好的设计方法。