C# 异常后停止函数
我在创建错误处理方法时遇到一些问题。遇到错误后,sub将继续,好像什么也没发生一样。这就是我所拥有的:C# 异常后停止函数,c#,C#,我在创建错误处理方法时遇到一些问题。遇到错误后,sub将继续,好像什么也没发生一样。这就是我所拥有的: try { int numericID = Convert.ToInt32(titleID); } catch(Exception) { errorHandling("Invalid Title"); } void errorHandling(string error) { MessageBox.Show("You have encou
try
{
int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
errorHandling("Invalid Title");
}
void errorHandling(string error)
{
MessageBox.Show("You have encountered an error: " + error, "Error");
return;
}
你想发生什么
一些常见的东西冒出了例外
try
{
int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
errorHandling("Invalid Title");
// rethrow the error after you handle it
//
throw;
}
或者您可以在errorHandling()
方法中记录错误
或者,您可以从引发异常的父方法返回
无论哪种方式,您都在catch
调用异常,并执行errorHandling()
方法,但此时catch
块的执行已完成。。。所以代码继续
不管你想发生什么让它发生在catch块中,或者您只是在沉默错误。如果不希望继续执行,则不允许继续执行,但需要在catch
块中显式地为其编写代码。捕获异常后调用方法。如果要结束编程,则需要在调用errorHandling后重新显示异常,或者调用System.Environment.Exit(1)编码>结束节目。我想如果你增加休息时间;除此之外,它可能会解决您的问题。或者你也可以尝试使用投掷 试试看
try
{
int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
errorHandling("Invalid Title");
return; // <---- perhaps you wanted to put the return here?
}
void errorHandling(string error)
{
MessageBox.Show("You have encountered an error: " + error, "Error");
// return; <-- does nothing
}
{
int numericID=转换为32(titleID);
}
捕获(例外)
{
错误处理(“无效标题”);
return;//在错误处理
方法末尾的return
语句不会终止程序。要终止程序,需要调用Application.Exit或System.Environment.Exit,具体取决于应用程序的类型捕获异常,然后调用另一个方法。如果不想继续,则应r在调用errorHandling
后返回或重试异常。这就是捕获和处理异常时发生的情况。如果希望方法抛出异常并中断程序,请不要将其包装在try-catch块中。好的,您捕获了异常,通过显示错误消息来处理。接下来要做什么。您的代码没有“不显示任何有关它的信息。遇到错误后,sub继续运行,就像什么也没发生一样。
这是您要求它做的。您捕获了错误并处理了它。如果希望错误继续传播,只需在catch
块中再次抛出它(在调用errorHandling
之后)。您可能希望签出Int32.TryParse
以避免所有异常。捕获错误后,我希望将其显示给用户(errorHandling),然后完全停止代码,允许用户再次与表单交互,并修复导致错误的问题。@MasonHanson然后您只想“返回”在catch
块的末尾。这仍然允许代码在遇到错误后执行。如果在try-catch语句之后有更多的代码需要运行,我希望只有在没有引发异常的情况下才能运行。如果有异常,代码将退出并允许用户与表单重新交互。编辑:啊,我看到return将退出cutent方法,但是如果try-catch语句是从辅助方法调用的,我必须使用return两次。谢谢你的帮助!
bool exceptionCaught = false;
....
try
{
int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
errorHandling("Invalid Title");
exceptionCaught = true;
return; // <---- perhaps you wanted to put the return here?
}
void errorHandling(string error)
{
MessageBox.Show("You have encountered an error: " + error, "Error");
// return; <-- does nothing
}
....
void OtherMethod()
{
if(!exceptionCaught)
{
// All other logic
}
}