InvalidOperationException: “Exception” in disguise? Or just the new ApplicationException?
Microsoft added ApplicationException with the idea that all exceptions that you made should derive from it. Fair point, you should be able to handle your own exceptions, right? The problem is that nobody used it, and therefore Microsoft changed its recommendation to NOT use it. It’s just lying there in the framework like an old aunt that just doesn’t want to go away (I still love you all, my dear aunts).
InvalidOperationException is also an exception that should be blown to hell. The description of the exception says this:
The exception that is thrown when a method call is invalid for the object’s current state.
What does that mean in the real world? When do exceptions get thrown in general? Well. When something unexpected has happened, as in when a method is called when it isn’t supposed to be. How else can an exception be raised? When not calling a method?
The InvalidOperationException is really like an Exception in disguise. Try to search for it in a couple of open source projects (or your own). It’s thrown a lot. It’s a poor man’s choice for exception handling. Ohhh, I’ve been guilty one too many times too. It’s so handy since it can be applied to all exceptional cases.
The reason why I wrote this post is that I was debugging an ASP.NET MVC application and found that MS throws it when an action cannot be found in a controller. The result is that an Internal Server Error page is shown instead of a File Not Found page. Sure, it’s an error in the application and the proper controller has been found. But does the browser care about which framework is used in the web server? No. File not found is therefore the proper status code.
Microsoft should have created an ActionNotFound exception instead and derived it from HttpException (and set the 404 status code in the constructor initialization).
Edit: I’ve filed a bug report for ASP.NET MVC: http://aspnet.codeplex.com/workitem/7588