尝试在 Java 中捕获 - 发生异常时会发生什么?

Try catch in Java - what happens when an exception occurs?

我有一个关于 try/catch 和 Java 中的例外的问题。我知道这应该是基本知识,但我想我错过了一部分对其工作原理的理解。例如,给定此代码:

String res = "";

try {
    res = methodThatCanThrowException();
    res = res + ".txt";
} catch (Exception e) {
    res = "somethingwentwrong.txt";
}

return res;

我能保证永远不会在 try 和 catch 块中设置 'res' 吗?如果在 try 块中的方法调用内部抛出异常,代码控制会直接转到 catch 块,对吗?有没有在 try 和 catch 块中都给 'res' 赋值的场景?

如果 methodThatCanThrowException 抛出异常,res 将不会在 try 块中分配,因此只有 catch 块会分配它(假设你修复你的捕获块)。

但是,即使在 res 已经赋值之后抛出异常,catch 块也会用新值覆盖它,所以如果两者都赋值也没有关系。

你是对的。如果 methodThatCanThrowException 抛出异常,它将跳转到 res = "somethingwentwrong.txt";。从来没有执行过两行的场景

如果try块内没有发生异常,catch块将永远不会执行。

另一方面,如果确实发生异常,则控制流从 try 块移动到您的 catch 块,并且 res 变量将被覆盖catch 块中的任何内容。

在您的情况下,res 将附加 methodTatCanThrowException() returns 和 .txtsomethingwentwrong.txt.

作为旁注,您可能还想查看 finally 块及其作用。

您可以获得的最佳答案来自 JLS - 14.20.1. Execution of try-catch:

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

...

If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed...

我不想粘贴整个部分,因为它很大,我强烈建议您通过它来更好地理解 try-catch-finally 的机制。

当try块内发生异常时,控制直接进入catch块,因此try块内不会执行其他代码,res的值也不会改变。 此外,当方法抛出异常时,它不会return任何东西。因此,如果出现异常,res 只会在 try catch 块外初始化时设置一次,然后在 catch 块内初始化。

从不超过两次