我有一个名为TryMe的方法,它有try 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窗体中。
问题是它只显示消息框,代码继续执行。
我想在异常捕获之后停止代码,而不是隐藏窗体。如果一切正常,它应该隐藏它。
也许我的概念是错的?
发布于 2013-05-14 15:05:03
最简单的修复方法是根据是否成功将您的函数更改为返回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
}发布于 2013-05-14 15:09:13
另一种选择是将控制流委托给调用者,因此:
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-14 15:18:08
你应该避免在任何地方调用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
}https://stackoverflow.com/questions/16536991
复制相似问题