Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java run code only if no exception is thrown in try and catch block?

How do I make it so the code runs only if there was no exception thrown?

With finally code runs whether there was an exception or not.

try {    //do something } catch (Exception e) {} //do something only if nothing was thrown 
like image 376
Muhammad Umer Avatar asked May 03 '15 21:05

Muhammad Umer


People also ask

Does all the code in a try block execute if no exception is thrown?

The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.

What happens if exception is not caught in try catch?

If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console. The message typically includes: name of exception type.

Can a try block run without catch in Java?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

How do you handle exceptions without try and catch?

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.


1 Answers

Here are two ways:

try {     somethingThatMayThrowAnException();     somethingElseAfterwards(); } catch (...) {     ... } 

Or if you want your second block of code to be outside the try block:

boolean success = false; try {     somethingThatMayThrowAnException();     success = true; } catch (...) {     ... } if (success) {     somethingElseAfterwards(); } 

You could also put the if statement in a finally block, but there is not enough information in your question to tell if that would be preferable or not.

like image 155
khelwood Avatar answered Sep 28 '22 17:09

khelwood