Exception Handling In C#

What is an exception?

An exception is an unforeseen error that occurs when a program is running. An exception is actually a class that derives from System.Exception class.

The System.Exception class has several useful properties, that provide valuable information about the exception.
  • Message - Gets a message that describes the current exception.
  • Stack Trace - Provides the call stack to the line number in the method where the exception occurred.
We use Try, Catch and Finally block for exception handling.
  • Try - The code that can possibly cause an exception will be in the Try block.
  • Catch- Handles the exception.
  • Finally- Clean and free resources that the class was holding onto during the program execution.
Specific exceptions will be caught before the base general exception, so specific exception blocks should always be on top of the base exception block. Otherwise, you will encounter a compiler error.

Note

It is a good practice to always release resources in the Finally block, because finally block is guaranteed to execute, irrespective of whether there is an exception or not.

InnerExceptions

The InnerException property returns the Exception instance that caused the current exception.