-1

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

4

2 回答 2

5

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

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

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

但是,在某些情况下,finally 块不会运行。有关更多详细信息,请参见此处:

于 2012-09-01T07:39:26.300 回答
1

仅当您的程序通过使用System.exit()或抛出 or 退出时才会发生这种情况(而Error不是将被捕获)。ThrowableException

尝试以下操作:

   public static void main(String[] args) {         
        try{
            System.out.println("START!");
            int i=0;
            while(true){
                i++;
                if(i > 10){
                    System.exit(1);
                }
            }
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        finally{
            System.out.println("this will not be printed!");
        }
    }
于 2012-09-01T07:50:58.063 回答