Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue loop iteration after exception is thrown

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 ?

like image 233
Dimitar Tsonev Avatar asked May 29 '13 15:05

Dimitar Tsonev


People also ask

How do you continue a loop even after an exception?

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.

How do I continue after exception is caught?

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.

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

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.

Does code continue after exception?

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.


2 Answers

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);
    }
}
like image 58
Servy Avatar answered Sep 22 '22 16:09

Servy


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;
    }
}
like image 30
Kenneth Avatar answered Sep 25 '22 16:09

Kenneth