Detailed InvalidCastException Goodness Comes to a VM Near You.

When you perform an invalid cast in Mono (trying to force one type into another with a cast) or JIT would throw an InvalidCastException. If you are lucky, you would get a line number (compile with -g, run with --debug), but if you had a complicated expression you would have no idea what the problem was.

A few weeks ago, in support of Marek's growing pains in tracking down some bugs, Zoltan checked in support for a new feature in the Mono runtime: --debug=casts. Now, When you pass this option to the runtime, it will report the type that you are trying to cast. This feature is not activated by default as it generates more code, and consumes more memory.

This sample:

	$ cat demo.cs
        class Test {
                static void Main ()
                {
                        string s = "hola";
                        object j = s;

                        object d = (Test) j;
                }
        }
	$ mono demo.exe

	Unhandled Exception: System.InvalidCastException: Cannot cast from source type to destination type.
	   at Test.Main () [0x00000] 

	$ mono --debug=casts demo.exe

	Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'Test'.
	  at Test.Main () [0x00008] in /tmp/demo.cs:10 
	

Awesome.

Posted on 16 Apr 2008 by Miguel de Icaza
This is a personal web page. Things said here do not represent the position of my employer.