Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between catch {} and catch {continue;} in a c# foreach loop?

Tags:

c#

foreach (Widget item in items)
{
 try
 {
  //do something...
 }
 catch { }
}


foreach (Widget item in items)
{
 try
 {
  //do something...
 }
 catch { continue; }
}
like image 823
Mark Jones Avatar asked Jun 10 '10 17:06

Mark Jones


People also ask

Why do we use multiple catch handlers?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.

Can we use continue in catch block?

There is no continue statement in flow. What you want to do is in case of any exception in loop, catch it in (child) catch block but do not roll back or throw exception, in this case it will continue to next record.

What is the difference between catch clause and finally clause?

The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.

What is the difference between the try catch block and throws clause?

Try-catch block is used to handle the exception. In a try block, we write the code which may throw an exception and in catch block we write code to handle that exception. Throw keyword is used to explicitly throw an exception. Generally, throw keyword is used to throw user defined exceptions.


2 Answers

catch { continue; } will cause the code to start on a new iteration, skipping any code after the catch block within the loop.

like image 147
Fredrik Mörk Avatar answered Oct 21 '22 04:10

Fredrik Mörk


The other answers tell you what will happen in your given snippet. With your catch clause being the final code in the loop, there's no functional difference. If you had code that followed the catch clause, then the version without "continue" would execute that code. continue is the stepbrother of break, it short circuits the rest of the loop body. With continue, it skips to the next iteration, while break exits the loop entirely. At any rate, demonstrate your two behaviors for yourself.

for (int i = 0; i < 10; i++)
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }

    Console.WriteLine("I'm after the exception");
}

for (int i = 0; i < 10; i++)
{
    try
    {
        throw new Exception();
    }
    catch
    {
        continue;
    }

    Console.WriteLine("this code here is never called");
}
like image 40
Anthony Pegram Avatar answered Oct 21 '22 05:10

Anthony Pegram