Does throwing an exception stop execution java?

3.2K    Asked by AmitSinha in Java , Asked on Oct 10, 2022

There is a recommendation not to use an Exception to control the flow of execution. This gives me a reason for doubt when I do something like this:


 public void initApplication(String input) {
        try {
            MyClass mClass = new mClass(input);
            saveToDatabase(mClass);
            updateSettingsTheAppIsReady();
        } catch (CancelPreparationsException e) {
            showErrorMessageToUser();
            doRollbacks();
        }

    }

mClass instantiation, save operation to a database, settings update may go wrong, each of them throw their own exceptions, which I catch within the methods/classes and throw my custom exception to stop the initApplication() method execution.

This sounds an easier way than having preconditions checking like:

Create a MyClass object.

Check the MyClass object is created then save it to db.

Ensure the object was saved in db then update settings.

Is it really not a recommended way of using the Exception to control the flow? Thank you.

Answered by Amit Sinha

The answer to your question - Does throwing an exception stop execution java is : I would say that this isn't controlling the flow of your application. This is handling an exceptional circumstance (i.e., failure of your code to perform what as it's meant to), which is what Exceptions are meant to accommodate.

The recommendation is more for circumstances like this:

public boolean itemExists(List list, MyObject object) {
    try {
        for(MyObject thisOne : list) {
            if(thisOne.getAttribute() == object.getAttribute()) {
                throw new Exception("found it");
            }
        }
    }
    catch(Exception e) {
        if(e.getMessage().equals("found it")) {
            return true;
        }
        throw e;
    }
    return false;
}

This controls the flow of the program based on normal execution. It should be pretty easy to see why this isn't ideal, simply for code readability, not considering aspects like performance, style, and best practices. What you have in the above code is fine. Throwing Exceptions for errors is what they're for. If you're throwing Exceptions simply to break out of loops or functions or are using them during the "intended" execution of your code, that's when you're going down the wrong path.



Your Answer

Answer (1)

In Java, throwing an exception doesn't necessarily halt the execution of your program by default. When an exception is thrown, the Java runtime system looks for an appropriate exception handler to catch and handle the exception.


If there's a try-catch block surrounding the code that throws the exception, and if there's a catch block that matches the type of exception thrown, then the execution will transfer to that catch block. After the catch block executes, the program continues its execution unless there's another exception thrown.

If no appropriate catch block is found, the exception will propagate up the call stack until it's caught or until it reaches the top-level exception handler, at which point the program will typically terminate and print out the exception stack trace.

However, if you throw an exception within a finally block, it will override any exception that occurred in the try block, but it won't stop the execution of your program. The original exception will still be thrown after the finally block completes.

So, in short, throwing an exception doesn't always stop the execution of a Java program, but it can halt the normal flow depending on how the exception is handled in your code.

1 Month

Interviews

Parent Categories