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?
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);
}
Various ways:
return
-
break
orcontinue
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.
There are several ways to do it:
Move the code into a new method and
return
from itWrap the try/catch in a
do{}while(false);
loop.
This is the code I usually do:
try
{
...........
throw null;//this line just works like a 'break'
...........
}
catch (NullReferenceException)
{
}
catch (System.Exception ex)
{
.........
}