我尝试过几次不同的捕获。我有一些“清理”代码,只有在抛出异常时才应该运行。我可以为每个异常添加相同的代码,但这会成为维护的噩梦。基本上,我喜欢像finally语句这样的东西,但是只有在抛出异常时它才能运行。
这可能吗?
答案 0 :(得分:18)
不幸的是,没有直接的支持。这样的事情怎么样
boolean successful = false;
try {
// do stuff
successful = true;
} catch (...) {
...
} finally {
if (!successful) {
// cleanup
}
}
答案 1 :(得分:1)
我唯一能想到的是在每个catch中设置一个变量,然后在最后检查该变量。
伪代码:
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
}
}
答案 2 :(得分:1)
我可以为每个例外添加相同的代码,但这会成为维护的噩梦。
或者如果你弄清楚'例外':
我可以为每个[地方]添加相同的代码,但这会成为维护的噩梦。
这就是为什么制作方法。
private void cleanup() { /* clean up */ }
...
try {
// oh noes
} catch (MyException me) {
cleanup();
} catch (AnotherException ae) {
cleanup();
}
维护麻烦不见了!
答案 3 :(得分:0)
为什么不使用简单的试用&捉?
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
}
答案 4 :(得分:0)
您可以尝试包装两层异常处理程序,并在完成常规处理后重新抛出异常:
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
}
不确定我是否真的喜欢这个解决方案...感觉有点像黑客。我可能宁愿在每个实例中看到显式处理的异常,即使这意味着重复调用某种共享清理函数。