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?
Yes, It does.
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.
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.
Yes, It is possible to have a try block without a catch block by using a final block.
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) { ... }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With