How can I exit try / catch block without exception exception in Java

I need a way to break out of the middle of a try / catch block without throwing an exception. Something like a break and a sequel for loops. Is it possible?

I get strange possibilities about throwing a custom exception (calling it "BreakContinueException"), which simply does nothing in its catch handler. I am sure this is very twisted.

So, any direct solution that I don't know about?

+43
java try-catch-finally
Jun 30 2018-11-11T00:
source share
7 answers

The correct way to do this is probably to break the method by putting the try-catch block in a separate method and using the return statement:

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

If the code contains many local variables, you can also consider using break from the marked block, as suggested by Stephen C :

 label: try { ... if (condition) break label; ... } catch (SomeException e) { ... } 
+40
Jun 30 '11 at 11:37
source share

You can always do this with break from the loop construct or labeled break , as indicated in the aioobies answer.

 public static void main(String[] args) { do { try { // code.. if (condition) break; // more code... } catch (Exception e) { } } while (false); } 
+27
Jun 30 2018-11-11T00:
source share

Different ways:

  • return
  • break or continue when in a loop
  • break to mark when in a tagged expression (see @aioobe example)
  • break when in a switch statement.

...

  • System.exit() ... although this is probably not what you mean.



In my opinion, “break to label” is the most natural (least distorted) way to do this if you just want to exit try / catch. But it can confuse beginning Java programmers who have never come across this Java construct.




By the way, return works when there is finally . But you should avoid using return in the finally block, because the semantics are a bit confusing and can give the reader a headache.

+11
Jun 30 2018-11-11T00:
source share

There are several ways to do this:

  • Move the code to the new method and return from it

  • Wrap try / catch in a do{}while(false); .

+7
Jun 30 '11 at 11:35
source share

In this example, in the catch block, I change the counter value and it will break during the 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 
+2
Mar 12 '13 at 9:18
source share

This is the code that I usually do:

  try { ........... throw null;//this line just works like a 'break' ........... } catch (NullReferenceException) { } catch (System.Exception ex) { ......... } 
+2
Aug 28 '13 at 16:11
source share

how about return it will do if not finally

+1
Jun 30 '11 at 11:35
source share



All Articles