#878 – Unhandled Exceptions in Static Constructors

If any exception is thrown from within a static constructor, a TypeInitializationException will be thrown, with an InnerException set to the original exception that occurred.  If this exception is not caught, the application will be terminated.

    public class Dog
    {
        public static string Motto { get; set; }

        static Dog()
        {
            Motto = "Serve humans and chase balls";
            throw new Exception("Static Dog constructor threw me");
        }
    }

878-001

#852 – How Exceptions Work

An exception is something that happens in your application at run-time that is unexpected and which requires special logic in order for the application to continue executing normally.

Here’s how exceptions work:

  • A particular piece of code calls a method, which in turn may call other methods
  • The call stack keeps track of the calling sequence that led to the currently executing method
  • At any given time, the code that is executing may decide to throw an exception, indicating that something unexpected happened
  • The method throwing an exception stops what it’s doing and control returns to the calling method
  • The calling method may decide to catch the exception, i.e. execute some code in response to it
  • If the calling method doesn’t catch the exception, control continues back up the stack until a method is found that does catch the exception
  • If no method catches the exception, it is unhandled