异常后停止功能
本文关键字:功能 异常 | 更新日期: 2023-09-27 18:06:04
我在创建错误处理方法时遇到一些问题。遇到错误后,sub继续运行,就像什么都没发生一样。这是我的文件:
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");
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
}
当异常被捕获时,它是其他函数中你想要中断执行的代码吗?只需要创建一个全局布尔值:
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
}
}
你希望发生什么?
一些常见的事情正在冒泡异常…
try
{
int numericID = Convert.ToInt32(titleID);
}
catch(Exception)
{
errorHandling("Invalid Title");
// rethrow the error after you handle it
//
throw;
}
或者您可以在您的errorHandling()
方法中记录错误。
或者您可以从抛出异常的父方法中获取return
。
无论哪种方式,您都是catch
异常,并且您正在执行errorHandling()
方法,但此时catch
块已经完成了它的执行…所以代码继续。
不管你想发生什么…让它在catch块中发生,或者您只是沉默错误。如果你不想继续执行,那么就不允许继续执行,但是你需要在catch
块中明确地为此编写代码。
errorHandling
方法末尾的return
语句不会终止程序。要终止您需要调用Application。Exit或System.Environment.Exit取决于应用程序的类型
在捕获异常后调用方法。如果你想结束程序,你需要在调用errorHandling后重新抛出异常,或者调用System.Environment.Exit(1);
来结束程序。
我想如果你加一个break;对于例外情况,它可能解决您的问题。或者你也可以尝试使用投掷。