【问题标题】:application does not appear to be catching an exception应用程序似乎没有捕获异常
【发布时间】:2018-09-27 08:25:41
【问题描述】:

我有一个 c# 控制台应用程序。我还有 Windows 任务调度程序,我每天早上都用它来执行我的 exe 文件。

我放置了一个 try catch 块(如下所示)来捕获任何错误并将异常写入文本文件。

try 块中的实际过程会创建一个 excel 实例并从工作簿中读取一些数据。代码正常工作。但是,当它失败时,错误似乎永远不会被捕获。

我有其他应用程序在 catch 块中使用相同的代码来输出异常并且知道这部分有效。只是似乎没有捕捉到异常。我可以看到计划的任务启动了文件。

更新

我已经检查了事件查看器(感谢下面的评论)并且可以看到任务已成功启动

 class Program
{
    static void Main(string[] args)
    {
        try
        {
            // do some work
        }
        catch(Exception ex)
        {
            // write output to log file
        }
    }
  }

【问题讨论】:

  • 你在 try 块中使用了任何类型的异步编程吗?
  • 是该错误从未被捕获,还是您的日志文件无法正常工作。弄清楚这一点,您可能会得到答案。除非它当然是 stakoverflow 或其他东西
  • 您“期待”什么样的异常?不记得了,但我认为 Excel 互操作会在某种对象中暴露 Excel 错误?
  • 我的意思是事件查看器

标签: c# .net exception-handling


【解决方案1】:

如果创建 excel 的过程与主线程在不同的线程或其任何部分,则 try-catch 块不会捕获异常,您需要使用 UnhandledException

基于此https://stackoverflow.com/a/3133249/2696230

将您的代码调整为以下内容:

class Program
{
    static void Main(string[] args)
    {
           System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        try
        {

            // do some work
        }
        catch(Exception ex)
        {
            // write output to log file
        }
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
      // handle the expception
    }
  }

【讨论】:

  • 我不太确定这会有所帮助
  • 我想我也遇到过类似的问题,但是这样解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-09
  • 1970-01-01
  • 2011-10-13
  • 2011-09-26
  • 1970-01-01
  • 2019-03-02
相关资源
最近更新 更多