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