开发者

How to make code run only if an exception was thrown?

I have a try with several different catches after it. I have some "cleanup" code that only should be run if there was an exception thrown. I could add the same code to each exce开发者_开发知识库ption, but that becomes a maintenance nightmare. Basically, I'd like something like the finally statement, but for it to only run if an exception was thrown.

Is this possible?


There is no direct support for this unfortunately. How about something like this

boolean successful = false;
try {
    // do stuff
    successful = true;
} catch (...) {
    ...
} finally {
    if (!successful) {
        // cleanup
    }
}


The only thing I can think of is to set a variable in each catch and then check for that variable in finally.

Pseudocode:

Boolean caught = false;

try {

    //risky code here

catch(err) {
    caught = true;
    // Do other stuff
}
catch(err) {
    caught = true;
    // Do other stuff
}
catch(err) {
    caught = true;
    // Do other stuff
}
finally {
   if (caught) {
       // Do clean up
   }

}


I could add the same code to each exception, but that becomes a maintenance nightmare.

Or if you blot out the 'exception':

I could add the same code to each [place], but that becomes a maintenance nightmare.

This is what methods are made for.

private void cleanup() { /* clean up */ }

...

try {
    // oh noes

} catch (MyException me) {
    cleanup();
} catch (AnotherException ae) {
    cleanup();
}

Maintenance hassle gone!


Why don't you just use simple try & catch?

try
{
    foo();
}
catch(Exception1 e1)
{
    dealWithError(1);
}
catch(Exception2 e2)
{
    dealWithError(2);
}
catch(Exception3 e3)
{
    dealWithError(3);
}

...

private void dealWithError(int i)
{
    if(i == 1) // deal with Exception1
    else if(i == 2) // deal with Exception2
    else if(i == 3) // deal with Exception3
}


You could try wrapping two layers of exception handlers, and rethrow the exception after you have done the common handling:

    try {
        try {
            // your code goes here

        } catch (Throwable t) {
            // do common exception handling for any exception
            throw t;
        }       

    } catch (NullPointerException nx) {
        // handle NPE
    } catch (Throwable t) {
        // handle any other exception
    }

Not sure I really like this solution though... feels like a bit of a hack. I'd probably rather see the Exception explicitly handled in each instance, even if this means repeating a call to some kind of shared cleanup function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜