Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

.net - Can I catch a missing dll error during application load in C#?

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

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());
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Extending Josh's answer.

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...