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?
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.
YES. If the exception was inside a try then code inside matching catch blocks or finally block will be executed.
When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.
If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With