-2

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.

testting
  • 19
  • 2
  • 1
    By "jump out of `try`", do you mean you want to run the code that is _after_ the `try...catch` statement? – Sweeper Apr 22 '20 at 10:00
  • Yes, I want to execute whats after catch block @Sweeper – testting Apr 22 '20 at 10:04
  • 1
    Does this answer your question? [How can I break from a try/catch block without throwing an exception in Java](https://stackoverflow.com/questions/6534072/how-can-i-break-from-a-try-catch-block-without-throwing-an-exception-in-java) – Bashir Apr 22 '20 at 10:06

1 Answers1

0

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 () {
    ...
}
Deepesh Choudhary
  • 660
  • 1
  • 8
  • 17