Exceptions in static constructors C# with Example



Exceptions in static constructors C# with Example

If a static constructor throws an exception, it is never retried. The type is unusable for the lifetime of the 
AppDomain. Any further usages of the type will raise a TypeInitializationException wrapped around the original 
 

exception. 
public class Animal 
{ 
static Animal() 
{ 
Console.WriteLine("Static ctor"); 
throw new Exception(); 
} 
public static void Yawn() {} 
} 
try 
{ 
Animal.Yawn(); 
} 
catch (Exception e) 
{ 
Console.WriteLine(e.ToString()); 
} 
try 
{ 
Animal.Yawn(); 
} 
catch (Exception e) 
{ 
Console.WriteLine(e.ToString()); 
} 
This will output: 
Static ctor 
System.TypeInitializationException: The type initializer for 'Animal' threw an exception. ---> 
System.Exception: Exception of type 'System.Exception' was thrown. 
[...] 
System.TypeInitializationException: The type initializer for 'Animal' threw an exception. ---> 
System.Exception: Exception of type 'System.Exception' was thrown. 
where you can see that the actual constructor is only executed once, and the exception is re-used. 

0 Comment's

Comment Form

Submit Comment