Java:抛出异常会杀掉它的方法吗?

rya*_*dlf 36 java exception-handling exception

例如:

public String showMsg(String msg) throws Exception {
    if(msg == null) {
        throw new Exception("Message is null");
    }
    //Create message anyways and return it
    return "DEFAULT MESSAGE";
}

String msg = null;
try {
    msg = showMsg(null);
} catch (Exception e) {
    //I just want to ignore this right now.
}
System.out.println(msg); //Will this equal DEFAULT MESSAGE or null?
Run Code Online (Sandbox Code Playgroud)

在某些情况下我通常需要基本上忽略异常(通常是在方法中抛出多个异常而在特定情况下无关紧要)所以尽管我为简单起见使用了可怜的例子,但showMsg中的返回仍然会运行或抛出实际上返回方法?

jac*_*obm 62

如果抛出异常,则不会运行该return语句.抛出异常会导致程序的控制流立即转到异常的处理程序(*),跳过其他任何方式.因此,如果抛出异常,特别是在您的print语句中.msgnullshowMsg

(*)除了finally块中的语句将运行,但这在这里并不重要.

  • 规则的另一个_exception_(没有双关语意)将是有问题的方法_catches_异常.你_can_在try块中显式抛出异常并在相应的catch块中自己捕获它.话虽这么说,你的答案可能会用你选择的单词来涵盖这个场景:"_...导致控制流立即进入exception's_**处理程序**". (8认同)