Pau*_*eed 1 c# windows exception-handling exception winforms
我有一个方法叫做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();
Run Code Online (Sandbox Code Playgroud)
方法定义在类文件中.调用方法是在窗体中.
问题是它只显示消息框并继续执行代码.
我想在异常捕获后停止代码并且不隐藏表单.如果一切正常,它应该隐藏它.
也许我的观念是错的?
最简单的修复方法是将您的函数更改为返回true/false,具体取决于它是否成功(即,如果TryMe方法没有出错,则仅隐藏表单):
public bool TryMe()
{
try
{
SomeMethod();
return true;
}
catch (Exception exception)
{
// log exception
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
if (CActions.TryMe())
{
this.Hide();
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是在显示消息后重新抛出异常,并让调用代码在try catch中处理它:
public void TryMe()
{
try
{
SomeMethod();
}
catch (Exception exception)
{
// log exception?
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
调用代码:
try
{
CActions.TryMe();
this.Hide();
}
catch (Exception ex)
{
// error handling
}
Run Code Online (Sandbox Code Playgroud)