简体   繁体   English

在catch区继续

[英]Continue in catch block

Is this: 这是:

// retry
for (int i = 0; i < length; ++i)
{
    try
    {
        sqlCommand.ExecuteNonQuery();
    }
    catch (SqlException e)
    {
        if (e.Number == 64)
        {
            continue;
        }
    }
}

equivalent to: 相当于:

// retry
for (int i = 0; i < length; ++i)
{
    try
    {
        sqlCommand.ExecuteNonQuery();
    }
    catch (SqlException e) { }
}

(since the loop will continue anyway in latter case) (因为在后一种情况下循环将继续)

What is the difference (if any)? 有什么区别(如果有的话)?

continue let you to skip the remaining statments in the current loop, and jump to the next iteration. continue让你跳过当前循环中的剩余语句,并跳转到下一个迭代。

Given the code we have right now, it makes no difference. 鉴于我们现在的代码,它没有任何区别。 Since there is no more code after if (e.Number == 64) { continue; } 因为if (e.Number == 64) { continue; }之后没有更多的代码if (e.Number == 64) { continue; } if (e.Number == 64) { continue; } . if (e.Number == 64) { continue; }

Both are identical !! 两者都是一样的!! But its not a good practice to have empty catch statement in your code .. The first piece of code is more appropriate .. you can add code to come out of the for loop or log an exception if the if (e.Number == 64) 但是在你的代码中使用空catch语句并不是一个好习惯..第一段代码更合适..你可以添加代码来出于for循环或者如果if (e.Number == 64)记录异常if (e.Number == 64)

For all practical intents, the code segments are equivalent. 对于所有实际意图,代码段是等效的。 There is an edge case, however, that in principle should never happen: what happens if the getter e.Number is evaluated and throws an exception? 然而,有一个边缘情况,原则上永远不应该发生: 如果评估getter e.Number并抛出异常会发生什么? If this were to happen, the code in the first example would throw, whereas the second example would continue. 如果发生这种情况,第一个示例中的代码将抛出,而第二个示例将继续。

Given that a property getter should never throw an exception , it's difficult to imagine this being a practical issue for .NET framework classes. 鉴于属性getter永远不会抛出异常 ,很难想象这是.NET框架类的实际问题。 But for this reason, the segments are (strictly speaking) not identical. 但由于这个原因,这些部分(严格来说)并不完全相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM