Common Exception Objects
Below is a summary of some of the more commonly used exception types in C#. As we mention before, all exceptions extend the System.Exception
class.
It is also possible to write your own exception type that inherits from System.Exception. You may find that your particular cause of error elicits a custom exception type. We won’t cover how to write custom exception objects in this book, but you can read about how to define your own exception here .
The examples in this table are excerpted from this page , where you can find several other commonly used exception types.
Common Exception Types in C#
As with catching, be specific with which types of exceptions you throw. Never throw an instance of the base Exception
class. If a built-in exception type works well based on it’s documented intended use, then use it! If there isn’t a built-in exception that matches your needs, then you can use a custom exception type.
Check Your Understanding
When should you write your own exception class?
- The error your code encounters is very specific and targeted.
- You know your code will produce an error, but you’re not sure which exception is the best fit.
- Writing custom exception classes is done by .NET developers only.
- Never, don’t do it.
Suppose you have created an empty array of Temperature objects :
Temperature[] temps = new Temperature[] { };
What, if any, exception would you expect to encounter when the following line executes:
double firstTemp = temps[0].Fahrenheit;
- No exception will be thrown —
temps[0].Fahrenheit
will returnnull
. NullReferenceException
— the object attemps[0]
is null.InvalidOperationException
— cannot access the object’s property.IndexOutOfRangeException
— the array is empty.