Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 682
Basil Musa Avatar asked Jun 30 '11 11:06

Basil Musa


People also ask

Does Break work in try-catch?

Yes, It does.

How do you catch an exception without throwing it?

Without using throws When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). If you re-throw the exception, just like in the case of throws clause this exception now, will be generated at in the method that calls the current one.

How do you handle exceptions without try and catch?

throws: The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

Can we skip catch block in try-catch?

Yes, It is possible to have a try block without a catch block by using a final block.


2 Answers

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) {     ... } 
like image 81
aioobe Avatar answered Sep 20 '22 22:09

aioobe


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); } 
like image 40
dacwe Avatar answered Sep 18 '22 22:09

dacwe