How can I break from a try/catch block without throwing an exception in Java

Basil Musa picture Basil Musa · Jun 30, 2011 · Viewed 114k times · Source

I need a way to break from the middle of try/catch block without throwing an exception. Something that is similar to the break and continue in for loops. Is this possible?

I have been getting weird throughts about throwing a custom exception (naming it "BreakContinueException") that simple does nothing in its catch handler. I'm sure this is very twisted.

So, any straight forward solution I'm not aware of?

Answer

aioobe picture aioobe · Jun 30, 2011

The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement:

public void someMethod() {
    try {
        ...
        if (condition)
            return;
        ...
    } catch (SomeException e) {
        ...
    }
}

If the code involves lots of local variables, you may also consider using a break from a labeled block, as suggested by Stephen C:

label: try {
    ...
    if (condition)
        break label;
    ...
} catch (SomeException e) {
    ...
}