java try-catch-finally递归问题 [英] java try-catch-finally recursion question

查看:449
本文介绍了java try-catch-finally递归问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Foo {

    public static void main(String[] args) {
        foo();
    }

    public static void foo() {
        try {
            System.out.println("try");
            foo();
        } catch (Throwable e) {
            System.out.println("catch");
            foo();
        } finally {
                System.out.println("finally");
                foo();
        }
    }
}

谁能解释这段代码的输出?

who can explain the output of this code ?

1.在Eclipse(无尽)客户端模式下输出:

1.output on eclipse (endless) client mode:



    try
    try
    ....


    ...
    ...
    tryfinallyfinally
    tryfinallyfinally
    try
    try
    try
    tryfinallyfinally
    tryfinallyfinally
    try
    tryfinallyfinally
    tryfinallyfinally
    try
    ....
    ....

2.在Linux(崩溃)服务器模式下输出:

2.output on linux (crash) server mode:



    try
    try
    ...

    ...
    try
    try
    try
    try
    try
    try
    MISSING EXCEPTION HANDLER for pc 0x00002aaaab1c53f0 and handler bci -1
       Exception:

     Compiled exception table :
    ExceptionHandlerTable (size = 3304 bytes)
    catch_pco = 700 (1 entries)
      bci -1 at scope depth 0 -> pco 11039
    catch_pco = 1736 (1 entries)
      bci -1 at scope depth 0 -> pco 11473
    catch_pco = 1756 (1 entries)
      bci -1 at scope depth 0 -> pco 11433
    catch_pco = 1776 (1 entries)

推荐答案

我想我从《 Java Puzzlers》一书中记得这一点. try块执行无限制的递归,这很快导致抛出StackOverflowError. try和catch阻止了 resume 递归,但是剩余堆栈相应较小.但是,随着每个递归调用的返回,剩余的堆栈会再次变大...

I think I remember this from the book "Java Puzzlers". The try block does an unbounded recursion which quickly results in a StackOverflowError being thrown. The try and catch blocks resume the recursion, but with a correspondingly smaller remaining stack. However, the the remaining stack gets larger again as each recursive call returns...

最终结果是一个调用图,该调用图形成一棵树,其深度取决于堆栈的大小;在主流JVM的默认堆栈大小下,树变得如此之大,以至于您不得不等待许多数十亿年的时间才能完全遍历它并终止程序.

The end result is a call graph that forms a tree with the depth depending on the size of the stack; with the default stack size of mainstream JVMs the tree gets so large that you'd have to wait for many, many billions of years for it to be completely traversed and the program to terminate.

编辑:这就是您在客户端模式下看到的内容:遍历调用图.在服务器模式下的Linux上,您看到的是JVM错误或硬件缺陷(有故障的RAM可能会产生这种影响).

That's what you're seeing in client mode: the traversal of the call graph. What you're seeing on Linux in server mode is either a JVM bug or a hardware flaw (faulty RAM can have this effect).

这篇关于java try-catch-finally递归问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆