I have a requirement where in program execution flow should continue even after throwing an exception.
for(DataSource source : dataSources) {
try {
//do something with 'source'
} catch (Exception e) {
}
}
If exception is thrown in the first iteration, flow execution is stopped. My requirement is even after throwing exception for the first iteration, other iterations should continue. Can i write logic in catch block?
If an exception is caught and not rethrown, the catch() clause is executed, then the finally() clause (if there is one) and execution then continues with the statement following the try/catch/finally block.
No. You cannot just jump back into the middle of a method.
The program execution is still interrupted if an exception is thrown from the divide method. Thus the "System. out. println(result);" method will not get executed if an exception is thrown from the divide method.
To print an exception without exiting the program, use a try/except block and assign the exception object to variable e using except Exception as e . Now, call print(e) in the except branch to print a simple error message.
Well first of all ,
There are 2 types of Exceptions. Checked & Unchecked.
Unchecked exceptions are the ones that your program cannot recover from. Like NullPointers, telling you that something is really wrong with your logic.
Checked exceptions are runtime exceptions, and from these ones you can recover from.
Therefore you should avoid using catch statemens looking for the "Exception" base class. Which are represent both times. You should probably consider looking for specific exceptions(normally sub-classes of Run-Time exceptions).
In short, there is much more into that.
You should also keep in mind that you shouldn't use exception handling as workflow. usually indicates that your architecture is somehow deficient. And as the name states, they should be treated as "exceptions" to a normal execution.
Now, considering you code :
for(DataSource source : dataSources) {
try {
//do something with 'source'
} catch (Exception e) { // catch any exception
continue; // will just skip this iteration and jump to the next
}
//other stuff ?
}
As it is, it should catch the exception and move on. Maybe there is something your not telling us ? :P
Anyway, hope this helps.
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