为什么这样的输出会来?

时间:2014-10-14 07:46:35

标签: java exception exception-handling try-catch

这可能很容易,但我不明白为什么输出结果为1 4.第9行的return语句的功能是什么?

public static void main(String[] args) {
    try{
        f();
    } catch(InterruptedException e){
        System.out.println("1");
        throw new RuntimeException();
    } catch(RuntimeException e){
        System.out.println("2");
        return;                    \\ Line 9
    } catch(Exception e){
        System.out.println("3");
    } finally{
        System.out.println("4");
    } 
        System.out.println("5");
}   
        static void f() throws InterruptedException{
            throw new InterruptedException("Interrupted");
    }

提前致谢。

6 个答案:

答案 0 :(得分:2)

你的function f()抛出InterruptedException,它被第一个catch块捕获(因此它打印1),但是这个catch块不能抛出其他异常(如果它没有被你的方法抛出),因此,没有其他catch块可以捕获您的excception,因此最终执行(最终在每种情况下执行除了那些愚蠢的无限循环情况)。你可以参考Exception thrown inside catch block - will it be caught again?

我希望它有所帮助。

总结一下,你可以从try block&中抛出任何异常。它将被捕获(如果有一个好的捕获块)。但是从catch块中只有那些异常可以抛出(并因此被你的方法引发)。

如果你从catch块中抛出异常,这些异常不会被你的方法抛出,那么它意味着更少,并且不会被捕获(就像你的情况一样)。

答案 1 :(得分:1)

正如您所看到f()抛出InterruptedException,因此它将首先打印 1 ,它位于第一个catch块内,然后 finally 将执行,因此它将打印的 4

答案 2 :(得分:1)

打印1是因为f()抛出InterruptedException。因为异常是在第一个catch块中处理的,所以不再在其他异常块中处理它。 finally语句总是运行,因此也会打印4。

答案 3 :(得分:1)

try{
    f();
} catch(InterruptedException e){
    System.out.println("1");
    throw new RuntimeException(); // this RuntimeException will not catch by 
                                  //following catch block
} catch(RuntimeException e){

您需要按照以下方式更改代码才能捕获它。

 try{
        f();
    } catch(InterruptedException e){
        System.out.println("1");
        try {
            throw new RuntimeException();// this RuntimeException will catch 
                                         // by the following catch 
        }catch (RuntimeException e1){
            System.out.println("hello");
        }
    } catch(RuntimeException e){
        System.out.println("2");
        return;
    } catch(Exception e){
        System.out.println("3");
    } finally{
        System.out.println("4");
    }
    System.out.println("5");

然后你出去了“

  1
  hello // caught the RunTimeException
  4 // will give you 2,but also going to finally block then top element of stack is 4
  5 // last print element out side try-catch-finally

答案 4 :(得分:1)

f()会引发InterruptedException,因此您获得了1。最后总是在最后调用,所以你得到4

答案 5 :(得分:1)

当f()抛出执行的InterruptedException时,

catch(InterruptedException e){
        System.out.println("1");
        throw new RuntimeException();
}

打印 - >的 1

最后在退出程序之前执行,

finally{
        System.out.println("4");
}

打印 - >的 4

返回后的代码不会执行但最终会被执行。