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();
}
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 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With