72

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?

Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Basil Musa
  • 8,198
  • 6
  • 64
  • 63

6 Answers6

66

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) {
    ...
}
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • @aioobe: What to do if the method is supposed to return something else than `void`? – Gruber Oct 01 '15 at 08:35
  • 1
    @Gruber, I don't think I understand the issue. In the first snippet, you would have to put an expression after the `return` keyword and include a return statement at the bottom of the method. – aioobe Oct 01 '15 at 11:37
27

You can always do it with a break from a loop construct or a labeled break as specified in aioobies answer.

public static void main(String[] args) {
    do {
        try {
            // code..
            if (condition)
                break;
            // more code...
        } catch (Exception e) {

        }
    } while (false);
}
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • 4
    Will vreaking this way run the finally {} block of the try catch? – Basil Musa Jun 30 '11 at 16:17
  • 5
    IMO, `do ... while(false)` should be considered as a poor alternative to a labeled statement. – Stephen C Jan 24 '18 at 03:07
  • 1
    I agree with @StephenC. You shouldn't use a loop unless you are planning on looping. It will be confusing to anybody who ever reads your code, including yourself in 2 months from now. – setholopolus Mar 03 '18 at 21:48
  • @BasilMusa When a block of code is broken out of with the `break` keyword, the block is considered to have "completed abruptly." The same applies when an exception is thrown; a block of code will be exited "abruptly." This is the converse of "normal" completion/exiting. `finally` blocks obtain execution when their respective `try` blocks complete normally *or* abruptly, so execution will actually go to the finally, if it exists, immediately before going to wherever you "broke" to. – Kröw Aug 19 '19 at 06:48
17

Various ways:

  • return
  • break or continue when in a loop
  • break to label when in a labeled statement (see @aioobe's example)
  • break when in a switch statement.

...

  • System.exit() ... though that's probably not what you mean.

In my opinion, "break to label" is the most natural (least contorted) way to do this if you just want to get out of a try/catch. But it could be confusing to novice Java programmers who have never encountered that Java construct.

But while labels are obscure, in my opinion wrapping the code in a do ... while (false) so that you can use a break is a worse idea. This will confuse non-novices as well as novices. It is better for novices (and non-novices!) to learn about labeled statements.


By the way, return works in the case where you need to break out of a finally. But you should avoid doing a return in a finally block because the semantics are a bit confusing, and liable to give the reader a headache.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
7

There are several ways to do it:

  1. Move the code into a new method and return from it

  2. Wrap the try/catch in a do{}while(false); loop.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
4

This is the code I usually do:

 try
 {
    ...........
    throw null;//this line just works like a 'break'
    ...........   
  }
  catch (NullReferenceException)
  { 
  }
  catch (System.Exception ex)
  {
      .........
  }
diwatu
  • 5,641
  • 5
  • 38
  • 61
  • 1) This is not valid Java. 2) The question is about breaking out of a `try` without throwing an exception. You are *explicitly* throwing an exception. – Stephen C Mar 04 '18 at 00:01
2

In this sample in catch block i change the value of counter and it will break while block:

class TestBreak {
    public static void main(String[] a) {
        int counter = 0;

        while(counter<5) {
            try {
                counter++;
                int x = counter/0;
            }
            catch(Exception e) {
                counter = 1000;    
            }
        }
    }
}k
Janek Bogucki
  • 5,033
  • 3
  • 30
  • 40
Fariba
  • 693
  • 1
  • 12
  • 27
  • 1) The question is about breaking out of a try without throwing an exception. You are throwing an exception under the covers, and in a way that is probably too difficult for the JIT compiler to optimize away. 2) Catching `Exception` is bad. – Stephen C Mar 04 '18 at 00:04