138

I came across this MSDN page that states:

Do not throw Exception, SystemException, NullReferenceException, or IndexOutOfRangeException intentionally from your own source code.

Unfortunately, it does not bother to explain why. I can guess the reasons but I hope that someone more authoritative on the subject might offer their insight.

The first two make some obvious sense, but the latter two seem like ones you would want to employ (and in fact, I have).

Further, are these the only exceptions one should avoid? If there are others, what are they and why should they, too, be avoided?

8
  • 24
    From msdn.microsoft.com/en-us/library/ms182338.aspx: If you throw a general exception type, such as Exception or SystemException in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.
    – Henrik
    Commented Mar 17, 2014 at 12:00
  • 3
    Why would you throw a NullReferenceException?
    – Rik
    Commented Mar 17, 2014 at 12:01
  • 5
    @Rik: similar to NullArgumentException which some people might confuse both. Commented Mar 17, 2014 at 12:02
  • 2
    @Rik extension methods, as per my answer Commented Mar 17, 2014 at 12:03
  • 3
    Another one you shouldn't throw is ApplicationException Commented Mar 17, 2014 at 12:35

5 Answers 5

120

Exception is the base type for all exceptions, and as such terribly unspecific. You shouldn’t ever throw this exception because it simply does not contain any useful information. Calling code catching for exceptions couldn’t disambiguate the intentionally thrown exception (from your logic) from other system exceptions that are entirely undesired and point out real faults.

The same reason also applies to SystemException. If you look at the list of derived types, you can see a huge number of other exceptions with very different semantics.

NullReferenceException and IndexOutOfRangeException are of a different kind. Now these are very specific exceptions, so throwing them could be fine. However, you still won’t want to throw these, as they usually mean that there are some actual mistakes in your logic. For example the null reference exception means that you are trying to access a member of an object which is null. If that’s a possibility in your code, then you should always explicitly check for null and throw a more useful exception instead (for example ArgumentNullException). Similarly, IndexOutOfRangeExceptions occur when you access an invalid index (on arrays—not lists). You should always make sure that you don’t do that in the first place and check the boundaries of e.g. an array first.

There are a few other exceptions like those two, for example InvalidCastException or DivideByZeroException, which are thrown for specific faults in your code and usually mean that you are doing something wrong or you are not checking for some invalid values first. By throwing them knowingly from your code, you are just making it harder for the calling code to determine whether they were thrown due some fault in the code, or just because you decided to reuse them for something in your implementation.

Of course, there are some exceptions (hah) to these rules. If you are building something that may cause an exception which exactly matches an existing one, then feel free to use that, especially if you are trying to match some built-in behavior. Just make sure you choose a very specific exception type then.

In general though, unless you find a (specific) exception that fills your need, you should always consider creating your own exception types for specific expected exceptions. Especially when you are writing library code, this can be very useful to separate the exception sources.

6
  • 3
    The third part makes little sense to me. Sure, you should rather avoid causing these errors to begin with, but when you e.g. write an IList implementation, it's not in your power to affect the indices requested, it's the caller's logic mistake when an index is invalid, and you are can only inform them of this logic error by throwing an appropriate exception. Why is IndexOutOfRangeException not appropriate?
    – user395760
    Commented Mar 17, 2014 at 12:10
  • 8
    @delnan If you are implementing IList, then you will be throwing a ArgumentOutOfRangeException as the interface documentation suggests. IndexOutOfRangeException is for arrays, and as far as I know, you can’t re-implement arrays.
    – poke
    Commented Mar 17, 2014 at 12:18
  • 2
    What might also be somewhat related, NullReferenceException is usually internally thrown as a special case of an AccessViolationException (IIRC the test is something like cmp [addr], addr, ie. it tries to dereference the pointer and if it fails with an access violation, it handles the difference between NRE and AVE in the resulting interrupt handler). So apart from semantic reasons, there's also some cheating involved. It might also help discourage you from checking for null manually when it's not helpful - if you're going to throw a NRE anyway, why not let .NET do it?
    – Luaan
    Commented Mar 17, 2014 at 12:53
  • In regard to your last statement, about custom exceptions: I have never felt the need to do this. Perhaps I'm missing out on something. Under what conditions would one need to craft a custom exception type in lieu of something from the framework? Commented Mar 18, 2014 at 11:17
  • 1
    Well, for smaller applications there might not be a need for it. But as soon as you create something more complex where individual parts work as independent “components” it often makes sense to introduce custom exceptions for custom error situations. For example, if you have some access control layer, and you try to execute some service although you are not authorized to do so, you might throw a custom “access denied exception” or something. Or if you have a parser that parses some file, you might have your own parser errors to report back to the user.
    – poke
    Commented Mar 18, 2014 at 11:31
39

I suspect the intent with the last 2 is to prevent confusion with inbuilt exceptions that have an expected meaning. However, I'm of the opinion that if you are preserving the exact intent of the exception: it is the correct one to throw. For example, if you are writing a custom collection, it seems entirely reasonable to use IndexOutOfRangeException - clearer and more specific, IMO, than ArgumentOutOfRangeException. And while List<T> might choose the latter, there are at least 41 places (courtesy of reflector) in the BCL (not including arrays) that throw bespoke IndexOutOfRangeException - none of which are "low level" enough to deserve special exemption. So yeah, I think you can justly argue that that guideline is silly. Likewise, NullReferenceException is kinda useful in extension methods - if you want to preserve the semantic that:

obj.SomeMethod(); // this is actually an extension method

throws a NullReferenceException when obj is null.

12
  • 3
    "if you are preserving the exact intent of the exception" - surely if that were the case the exception would be thrown without you having to test for it in the first place? And if you've already tested for it, then it's not really an exception?
    – PugFugly
    Commented Mar 17, 2014 at 12:08
  • 5
    @PugFugly take 2 seconds to look at the extension method example: no, that will not be thrown without you having to test for it. If SomeMethod() doesn't need to perform member access, it is incorrect to force it to. Likewise: take that point up with the 41 places in the BCL that create custom IndexOutOfRangeException, and the 16 places that create custom NullReferenceException Commented Mar 17, 2014 at 12:10
  • 16
    I would argue that an extension method should still throw a ArgumentNullException instead of a NullReferenceException. Even if the syntactic sugar from extension methods allows the same syntax as normal member access, it still works very differently. And getting a NRE from MyStaticHelpers.SomeMethod(obj) would be just wrong.
    – poke
    Commented Mar 17, 2014 at 12:23
  • 1
    @PugFugly BCL is “base class library”, basically the core stuff in .NET.
    – poke
    Commented Mar 17, 2014 at 12:24
  • 1
    I expect that at least some of the places that throw IndexOutOfRangeException in the BCL, does it as the “old versions” of the code used an array that throw IndexOutOfRangeException, so the new code was made to throw the same exception. Commented Mar 17, 2014 at 18:04
9

As you point out, in the article Creating and Throwing Exceptions (C# Programmming Guide) under the topic Things to Avoid When Throwing Exceptions, Microsoft does indeed list System.IndexOutOfRangeException as an exception type that should not be thrown intentionally from your own source code.

In contrast, however, in the article throw (C# Reference), Microsoft seems to violate its own guidelines. Here is a method that Microsoft included in its example:

static int GetNumber(int index)
{
    int[] nums = { 300, 600, 900 };
    if (index > nums.Length)
    {
        throw new IndexOutOfRangeException();
    }
    return nums[index];
}

So, Microsoft itself isn't being consistent as it demonstrates the throwing of IndexOutOfRangeException in its documentation for throw!

This leads me to believe that at least for the case of IndexOutOfRangeException, there may be occasions where that exception type can be thrown by the programmer and be considered an acceptable practice.

2
  • Isn't this 100% horrible code to put out in docs/articles i.e. what about: GetNumber(3); i.e. index == nums.Length Suggests at least some people writing MS docs are not clear about indexes starting at 0 and .Length == the number of items, this is not a good indicator of quality IMHO. (N.B. think this example is not not there anymore but... still) Commented Aug 26, 2023 at 2:16
  • if (index >= nums.Length) would have made a bit more sense! Commented Aug 26, 2023 at 2:20
3

Putting the discussion about NullReferenceException and IndexOutOfBoundsException aside:

What about catching and throwing System.Exception. I've thrown this type of exception in my code a lot and I was never screwed by it. Similarly, very often I catch the unspecific Exception type, and it also worked pretty well for me. So, why is that?

Usually users argue, that they should be able to distinguish error causes. From my experience, there are just a very few situations where you would want to handle different exception types differently. For those cases, where you expect users to handle errors programmatically, you should throw a more specific exception type. For other cases, I'm not convinced by the general best practice guideline.

So, regarding throwing Exception I don't see a reason to prohibit this in all cases.

EDIT: also from the MSDN page:

Exceptions should not be used to change the flow of a program as part of ordinary execution. Exceptions should only be used to report and handle error conditions.

Overdoing catch clauses with individual logic for different exception types are not best practice, either.

1
  • 3
    The exception message is still in place to tell what happened. I can't image, that you go and create a new exception type for each different error, just in case a consumer might want to distinguish those errors, programmatically.
    – uebe
    Commented Mar 27, 2020 at 15:02
1

When I read your question, I asked myself under what conditions one would want to throw the exception types NullReferenceException, InvalidCastException or ArgumentOutOfRangeException.

In my opinion, when encountering one of those exception types, I (the developer) feel concerned by the warning in the sense that the compiler is talking to me. So, allowing you (the developer) to throw such exception types is equivalent to (the compiler) selling the responsibility. For instance, this suggests the compiler should now allow the developer to decide whether an object is null. But making such a determination should really be the job of the compiler.

PS: Since 2003 I have been developing my own exceptions so I can throw them as I wish. I think it is considered a best practice to do so.

1
  • Good points. However, I think it would be more accurate to say that the programmer should let the .NET Framework runtime throw these types of exceptions (and that the programmer should handle them in an appropriate fashion).
    – DavidRR
    Commented Apr 25, 2014 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.