Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

InvalidOperationException: “Exception” in Disguise? Or Just the New ApplicationException?

5.00/5 (1 vote)
5 Nov 2010LGPL32 min read 7.9K  
Is InvalidOperationException: “Exception” in disguise? Or just the new ApplicationException?

Microsoft added ApplicationException with the idea that all exceptions that you made should derive it. Fair point, your 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 a disguise. Try to search in a couple of open source projects after it (or your own). It’s thrown a lot. It’s a poor man's choice to 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 Microsoft throws it when an action cannot be found in a controller. The result is that an Internal Server Error page is shown instead of an File not found exception. 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).

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)