Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Does Throwing An Exception Kill Its Method?

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?

like image 423
ryandlf Avatar asked Apr 12 '13 02:04

ryandlf


People also ask

Does throwing an exception stop the method Java?

When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed.

Does throwing exception break method?

YES. If the exception was inside a try then code inside matching catch blocks or finally block will be executed.

What happens when you throw an exception Java?

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.

Does code execution stop when exception is thrown?

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.


1 Answers

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.

like image 143
jacobm Avatar answered Oct 22 '22 19:10

jacobm