我可以在 C# 中的应用程序加载期间捕获丢失的 dll 错误吗? [英] Can I catch a missing dll error during application load in C#?

查看:14
本文介绍了我可以在 C# 中的应用程序加载期间捕获丢失的 dll 错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当找不到引用的 .dll 时,是否可以捕获异常?

Is it possible to catch the exception when a referenced .dll cannot be found?

例如,我有一个引用第三方dll的C#项目;如果找不到该 dll,则会引发异常.异常是 System.IO.FileNotFoundException,但我无法确定在哪里捕获它.以下代码似乎不起作用:

For example, I have a C# project with a reference to a third-party dll; if that dll cannot be found, an exception is thrown. The exception is a System.IO.FileNotFoundException, but I am unable to determine where to catch it. The following code did not seem to work:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        try
        {
          // code goes here
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.ToString());
        }
    }
}

推荐答案

扩展 Josh 的回答.

Extending Josh's answer.

.Net 中的程序集由 CLR 按需加载.通常,在使用该程序集中的类型的方法被 JIT 之前,不会尝试加载程序集.

Assemblies in .Net are loaded on demand by the CLR. Typically an assembly load won't be attempted until a method is JIT'd which uses a type from that assembly.

如果您无法通过 main 方法中的 try/catch 块捕获程序集加载失败,可能是因为您在 try/catch 中使用了程序集中的类型.所以异常发生在 main 方法实际运行之前.

If you can't catch the assembly load failure with a try/catch block in the main method, it's likely beceause you're using a type from the assembly within the try/catch. So the exception occurs before the main method is actually run.

尝试将 main 方法中的所有代码放在不同的函数中.然后在 try/catch 块中调用该函数,您应该会看到异常.

Try putting all of the code from the main method in a different function. Then call that function within the try/catch block and you should see the exception.

这篇关于我可以在 C# 中的应用程序加载期间捕获丢失的 dll 错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆