Thursday, December 08, 2005
Throw THINGS that are not exceptions !!!
This is my first time to know that we can throw types that are not
exceptions (not derived from system.exception)
Fortunately this cannot be done directly from CLS compliant languages like
C# and VB , but what if we are calling method M1() written by naughty C++ or
IL which throws an integer for example (throw 4). How can we catch this in
C# or VB ?
In .NET v1.x we can write :
Try
'call a naughty code that throws a non-exception
Catch
End try
This approach has 2 issues :
1- there is no variable for catching the exception
2- non-system exceptions are not accumulated on the stack trace so we cannot
debug .
In .NET v2.0 :
Non-system exceptions are wrapped up with
System.Runtime.CompilerServices.RuntimeWrappedException which derives from
System.Exception . And even more there is a switch to enable or disable this
: <Assembly:
System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(true)>
CLR Magic :
If assembly A (written in IL) throws a non-system exception . Assembly B
(written in C#) calls A . Assembly C (written in C++) call B.
1- if A catch it . It will see the non-system exception and never see that
it has been wrapped
2- if B catch it . It will see RuntimeWrappedException
3- if C catch it . It will see the non-system exception and never see that
it has been wrapped