Let's go over a few runtime-generated exceptions that .NET Framework supports. The framework uses these exceptions on valid statements that are being executed. Then, based on their type, an exception from the following table is thrown. For example, if the compiler tries to execute a division operation and if the denominator is zero, DividebyZeroException is thrown:
Exception |
Description |
ArithmeticException |
An exception that's triggered while performing arithmetic operations can be caught. |
ArrayTypeMismatchException |
When the value and type of the array don't match, this exception is thrown. |
DivideByZeroException |
When an attempt to divide an integer value by zero is made, this exception is thrown. |
IndexOutOfRangeException |
When an array is accessed with an index outside of its boundaries, this exception is thrown. |
InvalidCastException |
Converting a base type into an interface or derived type will cause this exception at runtime. |
NullReferenceException |
When you try to access an object that is null, this exception is thrown. |
OutOfMemoryException |
When the available memory for CLR is utilized, the new operator throws such exceptions. |
OverflowException |
While performing a division operation, for example, if the output is long and you try to push it to int, this exception is thrown. |
StackOverflowException |
Recursive calls usually cause such exceptions and indicate a very deep or infinite recursion. |
TypeInitializationException |
If you try to instantiate an abstract class, for example, this exception is thrown. |
Now that we've looked at compiler-generated exceptions, let's take a look at custom exceptions.