Let's say I have a code like this:
try
{
for (int i = 0; i < 10; i++)
{
if (i == 2 || i == 4)
{
throw new Exception("Test " + i);
}
}
}
catch (Exception ex)
{
errorLog.AppendLine(ex.Message);
}
Now, it's obvious that the execution will stop on i==2
, but I want to make it finish the whole iteration so that in the errorLog
has two entries (for i==2
and i==4
)
So, is it possible to continue the iteration even the exception is thrown ?
By putting a BEGIN-END block with an exception handler inside of a loop, you can continue executing the loop if some loop iterations raise exceptions. You can still handle an exception for a statement, then continue with the next statement.
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.
The answer for How to continue for loop after exception in java is we need to write our logic or code inside try catch block within the for loop.
If it is a RuntimeException ( or a derived exception class), your code will continue to execute, but if it is a normal Exception (or a derived class that does not derive from RuntimeException), that will crash the thread if uncaught, possibly crash the whole application.
Just change the scope of the catch
to be inside the loop, not outside it:
for (int i = 0; i < 10; i++)
{
try
{
if (i == 2 || i == 4)
{
throw new Exception("Test " + i);
}
}
catch (Exception ex)
{
errorLog.AppendLine(ex.Message);
}
}
Why do you throw the exception at all? You could just write to the log immediately:
for (int i = 0; i < 10; i++)
{
if (i == 2 || i == 4)
{
errorLog.AppendLine(ex.Message);
continue;
}
}
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