如何在c#中发生catch错误时跳过下一行执行?

Rai*_*med 1 c# visual-studio-2010 winforms

在一个函数中,我有几个try - catch块,如:

private void button1_click()
{
   try
   {
      // Lines of code
   }
   catch
   {
      // Lines of code
   }

   try
   {
      // Lines of code
   }
   catch
   {
      // Lines of code
   }
}
Run Code Online (Sandbox Code Playgroud)

如果catch块中的任何错误发生第一次捕获,我不希望下一行代码执行.

如何在第一次捕获错误时跳过下一个try块语句?

ror*_*.ap 8

你可以嵌套它们,如下所示:

try
{
    //lines of code

    try
    {
        //lines of code
    }
    catch
    {
        //lines of code
    }
}
catch
{
    //lines of code
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以return在第一个catch块中使用:

try
{
    //lines of code
}
catch
{
    //lines of code
    return;
}

try
{
    //lines of code
}
catch
{
    //lines of code
}
Run Code Online (Sandbox Code Playgroud)

请注意,对于后一种方法,您必须更加周到,因为如果您在需要释放资源的方法中执行此操作(您将在finally块中执行此操作),则返回将无法满足此要求.