Do not throw a NullReferenceException when validing “this” in an extension method

One pattern I’ve started running into is developers explicitly throwing a NullReferenceException when validating the “this” parameter of an extension method. public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action) { if (null == enumerable) { throw new NullReferenceException(); } // rest omitted } The desired behavior here is to make extension methods look even more…

3

The File System is unpredictable

One of the more frequent questions I answer on StackOverflow is a variation of the following.  I’m doing XXX with a file, how can I know if the file exists? The variations include verify no one else has the file open, if the file is in use, the file is not writable, etc ….  The…

11

NotImplementedException vs. NotSupportedException

In responding to a recent blog post, one of the readers, Jeremy Gray, noted that I was using a NotImplementedException where I should have been using a NotSupportedException.  At first I did not agree.  There was a method on an interface which my underlying object could not implement therefore I felt the choice of NotImplementedException…

5

When can you catch a StackOverflowException?

Answer: When you’re the one who threw it.  Starting with the CLR version 2.0, the policy for handling a StackOverflowException was changed.  User code can no longer handle the exception[1].  Instead the CLR will simply terminate the process.  This is not 100% true though.  User code can still handle StackOverflowExceptions which are artificially thrown.  That…


Custom Exceptions: When should you create them?

I think the best answer is: rarely.   It’s really hard to go straight to a justification here though.  I find that answering a different question will eventually shed led on when to create a new exception. "What are the benefits of creating a new/custom exception?" The answers I come up with or have heard before…

5