我有一个名为TryMe
的方法,它尝试使用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();
方法定义在类文件中。调用方法是在窗体中 问题是它只显示消息框并继续执行代码 我想在异常捕获后停止代码并且不隐藏表单。如果一切正常,它应该隐藏它 也许我的观念是错的?
答案 0 :(得分:7)
最简单的修复方法是将您的函数更改为返回true / false,具体取决于它是否成功(即,如果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
}
答案 1 :(得分: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
}
答案 2 :(得分:2)
您应该避免在任何地方调用MessageBox.Show()
,但应在应用程序的UI端(例如您的表单)。这被认为是一种不好的做法。所以我会修改NDJ的答案:
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
}
答案 3 :(得分:1)
如您的代码所述,Exception
被捕获,Message
属性传递给MessageBox
。这意味着,您的代码绝不会被中断或Exception
有机会冒泡。
旁注:在类try / catch(或任何其他方法)中显示MessageBox
被认为是一种不好的做法。原因很明显:它使您的类依赖于在图形应用程序环境中使用而违反类可重用性。最好沿着任何类型的应用程序可以处理的方法返回类型传播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