1

我有一个名为TryMetry catch 块并捕获他的异常的方法。
我从另一个班级给他打电话,但是当发生异常时,它不会停止代码执行。
例子:

public void TryMe()
{
    try
    {
        SomeMethod();
    }
    catch(Exception exception){
        MessageBox.Show(exception.Message);
    }
}


     //Method calling
     Actions CAactions = new Actions();
     CActions.TryMe();
     ///////////////////////////////////
     //If exception is handled it should stop to here.

     this.Hide();
     FormActions FormActions = new FormActions();

方法定义在类文件中。方法调用是windows形式的。
问题是它只显示消息框并且代码继续执行。
我想在异常捕获后停止代码而不是隐藏表单。如果一切正常,它应该隐藏它。
也许我的观念是错误的?

4

4 回答 4

7

最简单的解决方法是将您的函数更改为根据它是否成功返回真/假(即仅在 TryMe 方法没有出错时隐藏表单):

 public bool TryMe()
 {
  try
   {
    SomeMethod();
    return true;
   }
   catch (Exception exception)
   {
    // log exception 
    return false;
   }
  }

并这样称呼它:

 if (CActions.TryMe())
 {
   this.Hide();
 }

另一种选择是在显示消息后重新抛出异常,并让调用代码在 try catch 中处理它:

public void TryMe()
{
 try
 {
   SomeMethod();
  }
   catch (Exception exception)
  {
   // log exception? 
   throw;
  }
  }

调用代码:

   try 
   {
     CActions.TryMe();
     this.Hide();
   }
   catch (Exception ex)
   {
      // error handling
    }
于 2013-05-14T07:05:02.657 回答
2

另一种选择是将控制流委托给调用者,因此:

public void TryMe()
{
    try
    {
        SomeMethod();
    }
    catch(Exception exception){
       throw;
    }
}

并像使用它一样

 Actions CAactions = new Actions();
 try {
    CActions.TryMe();
    //continue, all ok.
 }
 catch(Excepiton ex) {
      //hide a form, exception happens inside a method
 }
于 2013-05-14T07:09:13.090 回答
2

You should avoid calling MessageBox.Show() anywhere, but on UI side of your application (e.g. your Form). It is considered a bad practice. So i would modify NDJ's answer:

public bool TryMe()
{
   try
   {
       SomeMethod();
       return true;
   }
   catch (Exception exception)
   {
       //insert some logging here, if YOU need the callstack of your exception
       return false;
   }
}

if (CActions.TryMe())
{
    this.Hide();
}
else
{
    MessageBox.Show(...); //insert some meaningful message, useful to END-USER here, not some "Null refrence exception!!11" message, which no one but you will understand
}
于 2013-05-14T07:18:07.597 回答
1

正如您的代码所述,Exception正在被捕获并将其Message属性传递给 a MessageBox。这意味着,您的代码绝不会被中断或有Exception机会冒泡。

MessageBox附带说明:在类 try/catch (或任何其他方法)中显示 a 被认为是一种不好的做法。原因很明显:它使您的类依赖于在图形应用程序环境中使用,这违背了类的可重用性。最好Exception沿任何类型的应用程序都可以处理的方法返回类型传播,例如包含Message和/或InnerException文本的字符串。

然后你可以做例如

string methodResult = myObject.MyMethod();
if(String.IsNullOrEmpty(myMethodResult)) //... everything worked out ok
...
else //well then at least you have an error message to work with
于 2013-05-14T07:13:34.090 回答