16.3. 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.
Note
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.
Type |
Description |
Example |
---|---|---|
|
Thrown by methods that verify that arguments are in a given range. |
|
|
Thrown by methods that do not allow an argument to be null. |
|
|
Thrown when an array is indexed improperly. |
Indexing an array outside its valid range: |
|
Thrown by methods when in an invalid state. |
Calling an |
|
Thrown when a |
|
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.
16.3.1. Check Your Understanding¶
Question
When should you write your own exception class?
The error the 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.
Question
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:
foreach( double temp in temps)
{
Console.WriteLine(temp);
}
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.