Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

For instance:

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?

I'm needing to essentially ignore exceptions in certain cases (usually when multiple exceptions can be thrown from a method and one doesn't matter in a particular case) so despite the pathetic example that I used for simplicity will the return in showMsg still run or does the throw actually return the method?

question from:https://stackoverflow.com/questions/15962228/java-does-throwing-an-exception-kill-its-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

1 Answer

The return statement will not run if the exception is thrown. Throwing an exception causes the control flow of your program to go immediately to the exception's handler(*), skipping anything else in the way. So in particular msg will be null in your print statement if an exception was thrown by showMsg.

(*) Except that statements in finally blocks will run, but that's not really relevant here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...