【问题标题】:How can i ignore error to continue project in c# code? [duplicate]如何在 C# 代码中忽略错误以继续项目? [复制]
【发布时间】:2017-02-01 14:00:37
【问题描述】:

我正在开发一个 Windows 窗体应用程序。当我在我的一个班级中运行项目时发生错误。 (见下图)

但是当我按下继续按钮时,项目运行良好。另外,我不能删除这行代码。如何忽略此错误以继续项目?

【问题讨论】:

  • 不要忽略它。修理它。在过去,该错误可能导致 BSOD
  • 通常你不应该忽略错误,它们是有原因的错误。东西坏了,修一下。如果您想处理它甚至忽略它,请查看 `try/catch' 块。
  • 我非常努力地修复了这个错误,但没有成功。这就是为什么我要忽略
  • 如果你可以绝对保证程序的其余部分在没有这部分代码成功运行的情况下可以正常运行,那么就去做吧。这仍然是一个糟糕的主意。
  • @hamid - 你没有意识到这个错误的严重性。不平衡的堆栈意味着您的应用程序处于不稳定状态,并且可能会进一步导致各种随机问题。如果你现在忽略这个问题,你以后会有问题,并且无法追溯到这个问题。

标签: c# windows winforms visual-studio error-handling


【解决方案1】:

使用 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
}

在 Visual Studio 中,您可以通过键入 try 并双击 Tab 键来插入 try-catch sn-p。

还有try-catch-finally。示例:

try {
    // code here
} catch (Exception) {
    // do something or nothing if caught
} finally {
    // perform some cleanup here
}

在 Visual Studio 中,您可以键入 tryf 并双击 Tab 键以插入 try-catch-finally sn-p。

您也可以使用 try-finally 进行一些清理而不会出现任何错误:

try {
    // code here
} finally {
    // perform some cleanup here
}

MSDN 上有关try-catchtry-finallytry-catch-finally 的更多信息。

但是,如果发生错误,则意味着有问题。谷歌一些关于它的信息。

【讨论】:

    【解决方案2】:

    您可以尝试使用 trycatch :

    try{
    //your code
    }
    catch(Exception ex)
    {
    //Log the exception 'ex'
    }
    

    【讨论】:

      【解决方案3】:

      您正在寻找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
      

      欲了解更多信息,请阅读C# - Exception Handling

      【讨论】:

        猜你喜欢
        • 2021-03-25
        • 2013-03-13
        • 2011-12-01
        • 1970-01-01
        • 2011-05-07
        • 1970-01-01
        • 2010-10-09
        • 2016-12-07
        • 1970-01-01
        相关资源
        最近更新 更多