代码之家  ›  专栏  ›  技术社区  ›  Mike Pateras

我想我正在处理的未处理的FileLoadException

  •  0
  • Mike Pateras  · 技术社区  · 14 年前

    Utility.Log("1");
    
    myThread = new Thread(new ThreadStart(delegate
    {
        Utility.Log("2");
    

    然后执行线程的其余部分。奇怪的是,尽管整件事都被包装在try/catch中,但我在日志文件(no 2)中只看到了1,并且得到了一个未处理的System.IO.FileLoadException。我也尝试过在try/catch中包装委托的整个主体,但是我仍然得到那个异常,事件查看器说异常的最顶层方法是那个方法。很奇怪。

    有什么办法可以追踪到这一点,或者至少可以正确地捕捉到异常?

    4 回复  |  直到 14 年前
        1
  •  2
  •   Hans Passant    14 年前

    FileLoadException是一个相当严重的灾难。当JIT编译器试图编译在线程中运行的代码时,会引发此问题。try/catch对无法捕获此异常,因为它已引发 之前 代码开始执行。换句话说,它会爆炸 进入try块。考虑到这是一个线程,你不能阻止你的程序崩溃到桌面。最后一个喘息是AppDomain.UnhandledException,e.ExceptionObject的InnerException属性告诉您到底出了什么问题。

    否则,此异常应始终易于修复。这是一个配置问题,JIT编译器会发现一个程序集的版本号错误,或者是该程序集的旧版本,诸如此类。如果无法从AppDomain.UnhandledException进行诊断,那么Fuslogvw.exe工具可以显示它是如何找到错误的程序集的。完全重建你的解决方案应该是解决问题的一半。

        2
  •  1
  •   jgauffin    14 年前

    你只发布了一部分代码,因此很难回答你的问题。所以这里有一个一般性的建议。

    public void MyMethod()
    {
        _myThread = new Thread(WorkerThread);
        _myThread.Start();
    }
    
    public void WorkerThread(object state)
    {
        try
        {
          Utility.Log("2");
        }
        catch (Exception e)
        {
           //log error
        }
    }
    
        3
  •  1
  •   Steve Townsend    14 年前

    原作 try..catch

    如果你想知道子线程中发生了什么,你必须给它自己的异常处理。听起来你是按照“我也试过用 try/catch ,但是需要修改代码来确认其正确性。

        4
  •  1
  •   honibis    14 年前

    您需要添加线程异常事件处理程序:

    只需在application.run之前添加处理程序,就可以捕获所有未处理的线程异常。

    来源于msdn:

    [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
    public static void Main(string[] args)
    {
        // Add the event handler for handling UI thread exceptions to the event.
        Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);
    
        // Set the unhandled exception mode to force all Windows Forms errors to go through
        // our handler.
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    
        // Add the event handler for handling non-UI thread exceptions to the event. 
        AppDomain.CurrentDomain.UnhandledException +=
            new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
        // Runs the application.
        Application.Run(new ErrorHandlerForm());
    }
    

    http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx

    推荐文章