有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (6) 个答案

  1. # 1 楼答案

    try { for (;;); } finally { System.err.println("?"); }
    

    在这种情况下,finally将不会执行(除非调用了不推荐使用的Thread.stop,或者通过工具接口调用了等效的Thread.stop

  2. # 2 楼答案

    System.exit关闭虚拟机

    Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.

    This method calls the exit method in class Runtime. This method never returns normally.

        try {
            System.out.println("hello");
            System.exit(0);
        }
        finally {
            System.out.println("bye");
        } // try-finally
    

    在上面的代码中,“再见”不会打印出来

  3. # 3 楼答案

    本文错误地引用了Sun教程

    注意:如果JVM在执行try或catch代码时退出,那么finally块将不会执行。同样,如果执行try或catch代码的线程被中断或终止,那么即使整个应用程序继续运行,finally block也不会执行

    如果您仔细查看sun教程中的finally block,它不会说“不会执行”,而是“可能不会执行” 以下是正确的描述

    Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    这种行为的明显原因是对系统的调用。exit()在运行时系统线程中处理,这可能需要时间来关闭jvm,同时线程调度器可以请求最终执行。所以finally被设计为始终执行,但如果您关闭jvm,jvm可能会在最终执行之前关闭

  4. # 4 楼答案

    来自Sun Tutorials

    Note: If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

    我不知道最后一个区块还有什么不执行的方式

  5. # 5 楼答案

    进一步说,任何不会导致JVM退出的东西都会导致finally阻塞。因此,以下方法:

    public static int Stupid() {
      try {
        return 0;
      }
      finally {
        return 1;
      }
    }
    

    将奇怪地编译并返回1

  6. # 6 楼答案

    与系统相关。退出时,也会出现某些类型的灾难性故障,最终阻塞可能无法执行。如果JVM完全耗尽了内存,它可能会在没有捕获或最终发生的情况下退出

    具体来说,我记得一个项目,我们愚蠢地试图使用

    catch (OutOfMemoryError oome) {
        // do stuff
    }
    

    这不起作用,因为JVM没有内存来执行catch块