没有 catch 块仍然继续执行,没有任何警告或错误

No catch block still execution continues without any warning or error

我有这个代码。在 aMethod() 中有 try 块,但没有 catch 块来处理抛出的异常。生成的输出是 finally exception finished。谁能给我解释一下这是怎么回事?

   public class Test 
    {  
        public static void aMethod() throws Exception 
        {
            try /* Line 5 */
            {
                throw new Exception(); /* Line 7 */
            } 
            finally /* Line 9 */
            {
                System.out.print("finally "); /* Line 11 */
            } 
        } 
        public static void main(String args[]) 
        {
            try 
            {
                aMethod();  
            } 
            catch (Exception e) /* Line 20 */
            {
                System.out.print("exception "); 
            } 
            System.out.print("finished"); /* Line 24 */
        } 
    }

您将 aMethod() 声明为 throws Exception,因此它可以抛出任何已检查的异常,而不必捕获任何内容。

  • finally 块总是被执行,异常与否*。这就是导致您看到的第一个打印输出 "finally" 的原因。
  • 接下来,未捕获的异常传播到 main,它在 catch 块中被捕获,产生 "exception".
  • 之后,你的程序打印"finished"完成输出。

这就是 finally 的工作原理。而且,如果你这样做

try {
    throw new Exception();
} catch (Exception e) {
    ...
} finally {
    ...
}

catchfinally 块中的代码将被执行。

* 在极端情况下,您可以构造一个不执行 finally 块就退出的程序,但这与示例中的代码无关.