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

How to skip next lines of execution when catch error is occurred in c#?

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

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

   try
   {
      // Lines of code
   }
   catch
   {
      // Lines of code
   }
}

如果在 catch 块中发生任何错误,比如第一个捕获,我不希望执行下一行代码。

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

你可以像这样嵌套它们:

try
{
    //lines of code

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

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

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

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

请注意,您必须对后一种方法多加考虑,因为如果您在需要释放资源的方法中执行此操作(您将在 finally 块中执行),那么return 无法容纳。

创建几个简单的方法,执行一些工作并在每个方法中放置 try-catch 块。

private void button_click(){
   Method1();
   Method2();
   // etc...
}

private void Method1(){
   try{ /**/ } catch { /**/ }
}

private void Method1(){
   try{ /**/ } catch { /**/ }
}

可以添加return布尔运算结果。

示例:return如果方法通过完成则为真,如果抛出异常则为假。

private void button_click(){
   bool r = Method1();

   if (!r) return;

   r = Method2();

   if (!r) return;

   r = Method3();  

   // etc...
}

private bool Method1(){
   bool r = true;
   try{ /**/ } 
   catch { 
      /**/
      r = false;
   }
   return r;
}

private bool Method2(){
   bool r = true;
   try{ /**/ } 
   catch { 
      /**/
      r = false;
   }
   return r;
}