Wednesday, July 1, 2009

Exception handling basics

Exceptions happens when a member cannot successfully do what it's designed to do. Exceptions can be generated by CLR, 3rd party library or by user code using throw keyword.


A catch block can specify type of exception to catch. This is called exception filter. The exception type should derive from Exception. In general do not specify Exception as the exception filter.

Inside the catch block you can either return a value or throw an exception depending on the situation you're in. (When to throw an exception). Difference between throw and throw ex.

A finally block enables you to clean up actions that are performed in try block. A finally block always runs, regardless of exception is happen. Note that sometimes finally block will throw exceptions as well.


Exceptions contains a property called StackTrace. It contains names of the methods in current call stack, together with file name and line number where exception was thrown for each method. You can use Environment.StackTrace to get stack trace information when no exception is being thrown.

Sometimes you shouldn't throw exceptions. See cost of exceptions and this (SO)

Some common exceptions in .NET

NotImplementedException (msdn)
See Why does NotImplementedException exists - SO

Handling business logic in exceptions
http://stackoverflow.com/questions/5378005/when-is-it-ok-to-use-exception-handling-for-business-logic
http://programmers.stackexchange.com/questions/15570/representing-business-rules-with-exceptions

Exceptions you should not throw (SO)
Since they doesn't give any meaningful information when writing your own code you should not throw,

  • Exception
  • SystemException
  • NullReferenceException and IndexOutOfRangeException are fine





ResourcesUnhandled Exception Processing In The CLR

0 comments:

Post a Comment

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook