while循环尝试块

Tin*_*bel -1 java while-loop

我试图在try/catch块中放置一个while循环.令我好奇的是,当while循环退出时,try catch不会被执行.有人可以解释实际发生的事情吗?我试图谷歌,但无法找到任何细节.

Mar*_*ers 5

我假设您的代码如下所示:

try
{
    while (...)
    {
        // ...
    }
}
catch (FooException ex)
{
    // This only executes if a FooException is thrown.
}
finally
{
    // This executes whether or not there is an exception.
}
Run Code Online (Sandbox Code Playgroud)

catch块仅在存在异常时执行.finally块通常执行是否抛出异常.所以你可能会发现你的finally块实际上正在被执行.您可以通过在那里放置一条导致控制台输出的输出来证明这一点.

但是,有些情况下finally块不会运行.有关详细信息,请参见此处

  • 听起来他指的是"终于"块,不是吗? (4认同)