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

时间:2015-02-01 14:34:10

标签: c# winforms visual-studio-2010

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

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

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

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

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

2 个答案:

答案 0 :(得分:8)

你会嵌套它们,如下:

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块中执行此操作),那么回报不适应。

答案 1 :(得分:-1)

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

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

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

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

您可以添加return bool操作结果。

示例:如果方法传递完成则返回true,如果抛出异常则返回false。

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;
}