C# 如何在c代码中忽略错误以继续项目?
我正在使用windows窗体应用程序。当我在我的一个类中运行项目时,会发生错误。(见下图)C# 如何在c代码中忽略错误以继续项目?,c#,windows,winforms,visual-studio,error-handling,C#,Windows,Winforms,Visual Studio,Error Handling,我正在使用windows窗体应用程序。当我在我的一个类中运行项目时,会发生错误。(见下图) 但当我按下“继续”按钮时,项目运行良好。另外,我不能删除这行代码。如何忽略此错误以继续项目?您可以尝试使用trycatch: try{ //your code } catch(Exception ex) { //Log the exception 'ex' } 使用try-catch: try { // code here } catch (Exception) { // do som
但当我按下“继续”按钮时,项目运行良好。另外,我不能删除这行代码。如何忽略此错误以继续项目?您可以尝试使用trycatch:
try{
//your code
}
catch(Exception ex)
{
//Log the exception 'ex'
}
使用try-catch:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
}
或者,如果要捕获指定的异常,请执行以下操作:
try {
// code here
} catch (/* exception class here */) {
// do something or nothing if caught
}
例如,如果要捕获NullReferenceException,请执行以下操作:
try {
// code here
} catch (NullReferenceException) {
// do something or nothing if caught
}
如果要使用异常数据,请将异常定义为变量,如下所示:
try {
// code here
} catch (Exception e) {
// do something or nothing if caught
}
在VisualStudio中,您可以通过键入try
并双击Tab键来插入try-catch片段
还有“最后一次尝试接球”。例如:
try {
// code here
} catch (Exception) {
// do something or nothing if caught
} finally {
// perform some cleanup here
}
在VisualStudio中,您可以键入tryf
并双击Tab键插入try-catch-finally片段
您也可以使用try finally执行一些清理,而不会出现任何错误:
try {
// code here
} finally {
// perform some cleanup here
}
有关MSDN的更多信息,以及
但是,如果发生错误,那就意味着出了问题。谷歌一些信息。您正在寻找
TryCatch
处理:
// some code
try
{
// "try" some code here
// You may put the line that may cause an error here
} catch(Exception ex)
{
// This part will get executed if above did not work (error - threw an exception)
// You may just keep it empty -> error will be ignored
// or log `ex` information
// or do something anything else
}
// control will continue - no crash
// some other code
有关更多信息,请阅读。不要忽略它。修好它。在过去,错误可能会导致BSODE。一般来说,你不应该忽略错误,它们是有原因的错误。有东西坏了,修理一下。如果你想处理它,或者甚至忽略它,那么看看“try/catch”块。我非常努力地修复这个错误,但是没有。这就是为什么我要忽略的原因,如果你能绝对保证程序的其余部分在没有这部分代码成功运行的情况下运行良好,那就去做吧。“这仍然是一个糟糕的想法。”哈米德-你没有意识到这个错误的严重性。不平衡的堆栈意味着您的应用程序处于不稳定状态,并且可能会在将来导致各种随机问题。如果您现在忽略此问题,以后将出现问题,并且无法将其追溯到此问题。