foreach (Widget item in items)
{
try
{
//do something...
}
catch { }
}
foreach (Widget item in items)
{
try
{
//do something...
}
catch { continue; }
}
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.
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.
The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result.
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.
catch { continue; }
will cause the code to start on a new iteration, skipping any code after the catch
block within the loop.
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");
}
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