在try catch中处理两个不同的连接关闭

Enr*_*man 0 java exception try-catch

如果你正在打开连接,那么你所做的就是试一试

try {
    doSomething();
} catch(Exception e) {
    // handle the exception
} finally {
    close();
}
Run Code Online (Sandbox Code Playgroud)

在我的场景中,我有两个catch和两个不同的结束:正常情况下为close(),如果抛出StrangeException则为closeStrange().

我提出了这样的事情:

try {
    doSomething();
} catch(StrangeException e) {
    closeStrange();
    throw new MyExc(e);
} catch(Exception e) {
    close();
    throw new MyExc(e);
}
close();
Run Code Online (Sandbox Code Playgroud)

我想知道以这种方式处理这种情况是否安全.

编辑:

可能还不清楚:我只想要其中一个结束.closeStrange()如果抛出StrangeException,close()如果抛出另一个Exception或none.

Jon*_*eet 5

不,你现在处理这个问题的方式并不安全:

  • 您没有使用finally块,因此抛出的任何非异常都将使您无需关闭连接
  • 你正在"处理"任何异常,这几乎肯定是不合适的

你可能想要:

boolean closedStrangely = false;
try {
   ...
} catch (StrangeException e) {
    closeStrangely();
    closedStrangely = true;
    throw e; // Or maybe not, or maybe throwing some custom exception
} finally {
    if (!closedStrangely) {
        close();
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果closeStrangely()抛出异常,则会尝试"正常"关闭它.如果您不想要这种行为,请调用之前设置closedStrangely为true .closeStrangely

编辑:即使你想在某些情况下抛出自定义异常,你几乎肯定应该抓住Exception.