I wanna jump out of try block,
How do i do it?
try
{
//some code
if()
{
// I want to break/ jump out from try block here if condition is true
}
else
{
}
//but it continues here
// More Code
}
catch()
{
}
How Do i jump out of it?
Any help would be appreciated.
Method 1
Try something like this:
try {
do {
...
if (condition)
break;
...
} while(false);
} catch () {
...
}
So the try block is just a do-while loop consisting all of the code. If the condition is true, it breaks out of the loop, and hence the try block.
Otherwise, it continues to the end and, because the condition of the do-while is false, comes out of the try block.
Note: If the if-statement is within another loop(other than this do-while loop), label this do-while loop, and later break to this label if condition is true.
Method 2
Make a custom Exception class and throw it only when the condition is met. Later, make the first catch statement to catch that custom exception. Like this:
try {
...
if (condition)
throw new CustomException();
...
} catch (CustomException e) {
// Condition was true
} catch () {
...
}
Related
Here is the skeletal for the code:
flag1=True
flag2=True
do {
try {
if (){
throw new IllegalArgumentException();
}
.
.
.
do {
if () {
}
else {
}
.
.
.
if () {
}
} while (flag2);
flag1 = false;
} catch (RuntimeException ex) {
flag1 = true;
} catch (Exception ex) {
flag1 = true;
} catch (Error ex) {
flag1= true;
}
}
} while (flag1);
}
I am using junit4 for testing. I need to cover all the try catch blocks for testing as well.
I wrote a test case satisfying the first if condition and hence throwing illegal argument exception, but after throwing the exception the code moves to the do loop with flag1 always staying true.
To start off it sounds like you might be a Java beginner. If that's the case, let me suggest reading up on exception handling in Java. I think that will make it easy for you to understand the cause of this behavior. Here are some quick tutorials on that topic from Oracle: https://docs.oracle.com/javase/tutorial/essential/exceptions/
With that said, here is my explanation of what is causing the behavior you described: 1. flag1 remains true. 2. looping doesn't stop.
1.
The reason why flag1 is not set to true is that when IllegalArgumentException is thrown, all code between the place it is thrown and the exception catch blocks will be skipped. This includes skipping the line flag1 = false;.
2.
The reason the while loops do not exit when IllegalArgumentException is thrown is that IllegalArgumentException inherits from RuntimeException as you can see here: https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html . This means that your catch block catch (RuntimeException ex) will catch the thrown exception. Thus, what will happen is that the code in the RuntimeException catch block (retry = true;) will be executed and then the execution will continue from after the try-catch block. Since this is still inside the outer do-while loop, looping will continue.
In the code below I was wondering if an exception was thrown in the for loop and the error message was added to the JSON object in the catch block, will the program return to the next iteration of the for loop after the exception was thrown? Or will it break the for loop and return the object?
JSONOBject obj = new JSONObject();
try
{
for(i=0; i<10; i++)
{
//do things in here that may throw an exception
obj.put("message","did not throw exception");
}
{
catch(Exception e)
{
obj.put("message",e.getMessage());
}
return obj;
An exception will terminate the method, because after the catch block the next statement is return.
If you want to continue the loop, put the entire try/catch inside the loop, as in:
for (.... whatever ...)
{
try
{
something
}
catch(Exception e)
{
obj.put("message",e.getMessage());
}
}
In this case the loop will execute all specified iterations, and each exception caught will add a new message to obj.
No - the loop will be exited from the point when the exception is thrown - after catch block is done with.
In a try block as soon as an error is thrown execution in that block stops and control jumps over to the catch block. Therefore in your case the rest of the for loop is not executed.
You can move the try catch into the for loop if you wish to continue through the for loop.
This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
What comes first - finally or catch block?
(8 answers)
Closed 9 years ago.
If we give return statement like this in try, what will be the order of execution
try{
--- ----
-----
return a;
}
catch{
}
finally{
}
Here what will be order of execution if there is return in try. Please let me know
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
finally always executes. If there is a return in try, the rest of try and catch don't execute, then finally executes (from innermost to outermost), then the function exits.
If there is a return in try, then control will go to finally block , execute the code present and then exit. So during this if in finally block there is any change to the any of the variable returned in try, and if that same variable is returned in finally then latest will be returned.
try {
i = 11;
return i;
} catch (Exception e) {
// TODO: handle exception
} finally{
i = 12;
return i; --> This will be returned
}
//return i;
}
But if there is only modification , no retrun in finally, the value returned in try will be the final value.
try {
i = 11; --> this will be returned
return i;
} catch (Exception e) {
// TODO: handle exception
} finally{
i = 12; -- this will be executed
}
//return i;
}
Finally is ALWAYS executed, after the evaluation of the return statement.
Whatever might be the case finally will always execute.
Incase of sucessful execution of try it will not execute catch block. If try blocks throws exception then catch block will execute
Normally order execution order of try-catch-finally is first try, then if exception trows and caught will execute the catch. If exception caught or not finally will always execute.
If return in your try, execution in try will stop there and will execute finally. if exception throws and caught before that return normal execution order will follows.
Let's run following code
public static void main(String[] args) {
String[] arr=getInfo();
for(String i:arr){
System.out.println(i);
}
}
public static String[] getInfo(){
String[] arr=new String[3];
try {
arr[0]="try";
return arr;
}catch (Exception e){
arr[1]="catch";
return arr;
}finally {
arr[2]="finally";
return arr;
}
}
Out put
try // return in try
null
finally // returning value in finally.
Now this out put explain the every thing you want. finally runs while there is a return in try.
If there a System.exit(0) in your try, finally is not going to execute.
in try-catch handling, when you return something from a try block, it will goes out of the scope of try-catch-finally.. because catch block only accept what is thrown by try.. not the thing that is returned and now when you have returned from the try block it wont reach the try end and finally wont be executed, it will go out try-catch-finally block, back to your code.
In Java docs I'm reading this:
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
When would you ever exit a try block with a break or continue ? The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
When would you ever exit a try block with a break or continue?
When you have a try inside a loop; e.g.
for (Cat cat : cattery) {
try {
cat.removeFromCage();
cat.healthCheck();
if (cat.isPedigree()) {
continue;
}
cat.spey();
} finally {
cat.putBackInCage();
}
}
OK ... so there are more elegant ways of writing that "code" ... but it is just an illustration.
The only scenarios I can think of is you are running a loop inside of a try block and you exit using a break/continue but that should just exit outside of a loop and not the try block itself right?
That is right.
FWIW, any piece of code that involves breaking out of a try block or returning from a catch or finally or any of the other "edge case" things should probably be simplified. The JLS specifies clearly what happens in these scenarios ... but that doesn't mean you should use them in a real program.
Java has labels. And labels usually used with break and continue operator. So, code:
outer: for (int i=0; i < 1; i++){
for (int j = 0; j < 1; j++) {
System.out.println("j:"+j);
continue outer;
}
System.out.println("i:"+i);
}
will print only "j:0"
And because break and continue are 'labeled', you can use "try" statement inside loop block, and inside that block you can try to call "continue" or "break outer_loop". But "finally" statement prevents that exit, as it described in your citation.
For a completely contrived example:
import java.io.*;
public class Foo {
public static void main(String[] args) throws IOException {
for (int i = 0; i < 10; i++) {
File file = new File("file-" + i);
FileWriter out = null;
try {
out = new FileWriter(file);
if (file.exists()) return;
out.write("Number " + i);
if (i % 2 == 0) continue;
else if (i % 3 == 0) break;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
out.close();
}
}
}
}
It's perfectly natural that you might want to return, break, or continue (or throw an exception) inside a try. In this example, if the finally weren't guaranteed to execute, you'd have a resource leak.
And yes, this particular problem is solved by try-with-resource in JDK7.
Yes, break/continue should only affect the loop, not the try/catch/finally block. The doc is just pointing out that it is easy to accidentally miss (not execute) a block of cleanup code when trying to handle exceptions, especially with those sneaky breaks and continues that change the flow!
The finally block should always be executed, unless System.exit() is called or the JVM crashes!
Yes possible, Using break statement we can exit try block with help of label and without using loop.
tryLabel:
try {
if(true)
break tryLabel;
System.out.println("try");
}catch(Exception e) {
System.out.println("catch");
e.printStackTrace();
}finally{
System.out.println("finally");
}
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 or continue 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 it
Wrap 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)
{
.........
}
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