Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception with try-catch and loop in Java

In Java, what is the difference (in term of performance) between:

for (int i = 0; i < count; i++) {
    try {
        // code that throws Exception
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and

try {
    for (int i = 0; i < count; i++) {
        // code that throws Exception
    }
} catch (Exception e) {
    e.printStackTrace();
}
like image 752
Martin08 Avatar asked Jun 12 '11 19:06

Martin08


People also ask

Can you use try catch in a loop Java?

For example in your code you could surround your try/catch in a while loop that will keep looping until the user has successfully entered a number.

How do you continue a loop after catching exception in try catch?

How do you continue a loop after catching exception in try catch Python? Use a for-loop to continue catching exceptions with a try-except block. Place a try-except block inside of a for-loop to continue catching exceptions with the try-except block.

How do you handle exceptions in a for loop in Java?

Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.

Can I put try catch inside for loop?

If you put the loop inside try-catch block, the moment it raises any exception you will exit the loop. If you put try-catch inside the loop, then the loop will continue to run even if there are exceptions.


2 Answers

In your first version the loop continues if it hits an exception, in the second version the loop continues after the catch block. That is the most important difference of those code snippets.

like image 110
driis Avatar answered Sep 24 '22 14:09

driis


You can use both, but it all depends on what you want it to do. If you want to continue the execution after the loop finishes once then you do it the first way. If you want to catch an exception then stop executing the loop then you do the second. Performance wise it all depends on what you want to do with it.

like image 36
RMT Avatar answered Sep 22 '22 14:09

RMT