Does throwing an exception stop execution java?

2.8K    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

Interviews

Parent Categories