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

Java:抛出异常会杀死它的方法吗?,java,exception,exception-handling,Java,Exception,Exception Handling,例如: 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 = showMs

例如:

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?

我需要在某些情况下基本上忽略异常(通常是当一个方法可以抛出多个异常,而一个异常在特定情况下并不重要时)因此,尽管我为简单起见使用了一个可怜的示例,showMsg中的return是否仍然运行,或者throw是否实际返回了该方法?

如果抛出异常,
return
语句将不会运行。抛出异常会导致程序的控制流立即转到异常的处理程序(*),从而跳过任何其他阻碍。因此,特别是如果
showMsg
引发异常,则打印语句中的
msg
null


(*)除了
finally
块中的语句将运行外,这与此处无关。

您的代码已经显示了throw的功能。避免抛出
new
异常,它会丢失调用堆栈。@jahroy我不这么认为,最后,即使在异常运行之后也会运行块运行该代码应证明msg为null,因为引发了异常。@MartinV.-是的。。。在一瞬间,我想到了我愚蠢的总括语句,并将其删除。该规则的另一个例外(没有双关语的意思)是,如果所讨论的方法捕捉到了该例外。您可以在try块中显式抛出异常,然后自己在相应的catch块中捕获它。也就是说,您的答案可能会用您选择的词语来覆盖这个场景:“……导致控制流立即转到异常的处理程序”。如果您从finally块中返回某个内容,那么尽管抛出了异常,它仍然会被返回。