What is exception or exception handling?

An exception is an unexpected or exceptional condition that occurs during the execution of a program, disrupting its normal flow. Exception handling is a mechanism in programming languages, including C#, that allows developers to manage and respond to these exceptional conditions in a controlled and systematic manner.

When an exceptional situation arises during program execution, such as attempting to divide by zero, accessing an out-of-bounds array element, or encountering an I/O error, the program raises an exception. This exception object contains information about the error, including the type of exception, a message describing the error, and the stack trace, which shows the sequence of method calls that led to the exception.

Exception handling enables developers to catch and handle these exceptions, preventing them from causing the program to crash or produce incorrect results. The primary components of exception handling are the 'try', catch, and optionally, the finally blocks:

  1. 'try' block:
    • The 'try' block is a section of code where developers place the statements that may raise exceptions. It is the code that needs to be protected against unexpected errors.
  2. 'catch' block:
    • The 'catch' block is used to handle the exceptions that occur in the corresponding 'try' block. If an exception occurs in the 'try' block, the runtime searches for a matching 'catch' block that can handle that specific type of exception.
    • Multiple 'catch' blocks can be used to catch different types of exceptions or handle them differently.
  3. 'finally' block (optional):
    • The 'finally' block contains code that is executed regardless of whether an exception occurred or not. It is used for cleanup tasks, such as releasing resources or closing files, that need to be performed regardless of the exception outcome.

When an exception is thrown in the 'try' block, the runtime looks for a matching 'catch' block. If a matching ''catch'' block is found, the code inside that block is executed to handle the exception. If there is no matching 'catch' block, the exception propagates up the call stack to higher-level code until it is caught and handled or until the program terminates.

Exception handling allows developers to:

  • Gracefully recover from unexpected errors without crashing the program.
  • Provide informative error messages for users or log errors for debugging purposes.
  • Implement robust error-handling logic to handle exceptional situations appropriately.
  • Ensure that critical resources are properly released even in the presence of errors.

By using exception handling effectively, developers can create more reliable and user-friendly applications that can gracefully recover from errors and maintain a high level of resilience.

Let us 'try' to understand with division by zero example:



using System;

class Program
{
    static void Main()
    {
        divideByZeroException();
    }

  static void divideByZeroException()
  {
	try
	{
	  int v1 = 100;
	  int v2 = 0;
	  int result = v1 / v2; 
	  Console.WriteLine(result); 
	}
	catch (Exception ex)
	{
	  Console.WriteLine(ex);
	}
	finally
	{
	  Console.WriteLine("finally block");
	}
  }
}

By invoking above method “'divideByZeroException()'” exception will be thrown. And you can also see that 'finally' block is also executed even through the exception has occurred.

Output: