.NET, Archive, C#

Throwing More Than Just Exceptions

Jason / January 23, 2007

It is a little known fact (and probably for the best) that the CLR can throw and catch more than just System.Exception and its children. In fact, the CLR can use any type as if it was an Exception.

.assembly ExceptionTestAssembly {}

.class public ExceptionTest { //custom class
//note that ExceptionTest does NOT extend System.Exception
.method public void .ctor(){
.maxstack 1

.method static void main() il managed{
.entrypoint //program entry point...
.try {
newobj instance void ExceptionTest::.ctor()
throw //throw a random object

} catch ExceptionTest { //catch the random object
ldstr "Random object caught"
call void [mscorlib]System.Console::WriteLine(string)
leave.s OUT

OUT: ret
read more