c# - Why are exceptions in a static constructor wrapped in TypeInitializationException -


the exception static constructor wrapped in typeinitializationexception. consider 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 program is

system.typeinitializationexception 
  1. what reasons wrapping exception in typeinitializationexception ?
  2. why original exception not returned ?

what reasons wrapping exception in typeinitializationexception ?

exceptions in static constructors difficult. basic issue execution context of exception vague. cli not give specific promise when constructor runs. guarantee run enough, how unspecified.

so dooms-day scenario without exception being wrapped vague bug report user "i nullreferenceexception when click save button". you'll study savebutton_click() event handler no hard look, you'll never find reason exception. occurred in code that's far removed event handler method, code ran @ unpredictable time.

by wrapping in typeinitializationexception, you'll know look.

why original exception not returned ?

it is returned, innerexception of tie. forgetting @ standard oversight. if ever write try/catch code never make mistake of displaying message property of exception caught. innerexception important too. favor displaying string generated exception object's tostring() method. gobbledegooky user essential you. avoid gobble logging or hiding details can revealed "details" button in error dialog.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -