robor
robor

Reputation: 3089

Why are exceptions in a static constructor wrapped in TypeInitializationException

The exception from a static constructor is wrapped in a TypeInitializationException. Consider the example below

using System;
namespace ConsoleApp
{
class Program
{
    static void Main(string[] args)
    {
        try
        {
            new MyClass();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.GetType().ToString());
        }
    }

    public class MyClass
    {
        static MyClass()
        {
            throw new Exception();
        }
    }
}
}

The output of the program is

System.TypeInitializationException
  1. What are the reasons for wrapping the exception in a TypeInitializationException ?
  2. Why is the original exception not returned ?

Upvotes: 3

Views: 961

Answers (2)

Hans Passant
Hans Passant

Reputation: 941397

What are the reasons for wrapping the exception in a TypeInitializationException ?

Exceptions in static constructors are difficult. Basic issue is that the execution context of the exception is very vague. The CLI does not give any specific promise exactly when the constructor runs. Only guarantee is that it will run soon enough, how soon is unspecified.

So a dooms-day scenario without the exception being wrapped is that you get a vague bug report from a user like "I get a NullReferenceException when I click the Save button". You'll study your SaveButton_Click() event handler but no matter how hard you look, you'll never find a good reason for that exception. It occurred in code that's far removed from the event handler method, code that ran at an unpredictable time.

By wrapping it in TypeInitializationException, you'll know where to look.

Why is the original exception not returned ?

It is returned, it will be the InnerException of the TIE. Forgetting to look at it is a standard oversight. If you ever write try/catch code then never make the mistake of only displaying Message property of the exception you caught. The InnerException is important too. Strongly favor displaying the string generated by the exception object's ToString() method. It is gobbledegooky to the user but essential to you. Avoid the gobble with logging or hiding details that can be revealed with "Details" button in the error dialog.

Upvotes: 7

MStodd
MStodd

Reputation: 4746

Static constructors are called on initialization, so although it's your static constructor that's failing, it's the type initalizer that's calling that, so that's the exception you get: https://msdn.microsoft.com/en-us/library/k9x6w0hc.aspx

Upvotes: 1

Related Questions