12 November 2016

Effect of exceptions while initializing the static members

Recently I encountered an error saying The type initializer for class threw an exception from a .NET windows service. The error was thrown while accessing any members/methods of a class. The error kept happening until the .NET Windows service was restarted.

After digging deeper into application error logs and analyzing the code in depth, I learnt the below:

  1. The offending class had static variables. One of the static variables was getting initialized by invoking DB repository method to get configured value.

    private static decimal minInsurancePremuimAmount = InsuranceConfigRepository.GetMinPremuimAmount();
  2. The database repository method was throwing exception when failed to fetch the data from Database Server in case of any transient error,etc.

    catch(Exception ex)
      // Log and throw the exception
      throw ex;
  3. When the offending class was first accessed, .NET framework tried to initialize the static variables. When it tried to initialize the minInsurancePremuimAmount, it resulted in a SQLException because Database server was not accessible at that time.
  4. So .NET framework could not complete the class initialization logic. Hence application was giving the error until it restarted.

    The type initializer threw an exception.

What was the fix?

  1. So taking clue from the issue, code changed to ensure static members initialization logic will never throw the exception up the call stack. In case of any errors happened during the static members initialization, such Exceptions just eaten and logged for DEBUG purposes.
  2. In the offending class, the internal logic was modified.

    Before accessing such static members, the members were NULL checked. If they were still NULL, the code was added to initialize the variable.

    This way even if there is an exception, only the current method invocation would fail, but not any future method invocations will result in the error "type initializer threw an exception".

1 comment:

  1. Good information for beginners on exceptions regarding the .NET applications. To gain hands on experience on all such kind of software, go through the Professional Web Design Company