Exceptions

Exceptions in C# are used to manage errors and unusual conditions that arise during program execution. They provide a robust mechanism for detecting and responding to runtime problems, allowing your program to handle unexpected situations gracefully. C# employs a try-catch-finally syntax for exception handling.

Basics of Exception Handling

  • Try Block: This section contains the code that may potentially throw an exception.
  • Catch Block: This section is designed to handle the exception. You can have multiple catch blocks to address different types of exceptions.
  • Finally Block: This is an optional section that contains code for cleaning up resources. It will be executed regardless of whether an exception was thrown or not.

Example

using System;

class Program
{
  static void Main()
  {
      try
      {
          // Prompt user to enter two numbers
          Console.Write("Enter the numerator: ");
          int numerator = Convert.ToInt32(Console.ReadLine());
          Console.Write("Enter the denominator: ");
          int denominator = Convert.ToInt32(Console.ReadLine());

            // Perform division
          int result = Divide(numerator, denominator);
          Console.WriteLine($"Result: {result}");
      }
      catch (DivideByZeroException ex)
      {
          // Handle divide by zero exception
          Console.WriteLine("Error: Cannot divide by zero.");
          Console.WriteLine($"Exception Details: {ex.Message}");
      }
      catch (FormatException ex)
      {
          // Handle format exception (e.g., invalid input)
          Console.WriteLine("Error: Invalid input. Please enter numeric values.");
          Console.WriteLine($"Exception Details: {ex.Message}");
      }
      catch (Exception ex)
      {
          // Handle any other exceptions
          Console.WriteLine("An unexpected error occurred.");
          Console.WriteLine($"Exception Details: {ex.Message}");
      }
      finally
      {
          // Clean up resources (if any)
          Console.WriteLine("Division operation completed.");
      }
  }

    static int Divide(int x, int y)
  {
      return x / y;
  }
}

Example of Exception Handling

  1. Try Block:
    • The try block contains code that might throw an exception. In this example, it includes code to read input from the user and perform division.
  2. Catch Blocks:
    • Multiple catch blocks are used to handle different types of exceptions:
      • DivideByZeroException: Catches and handles division by zero errors, displaying an appropriate message.
      • FormatException: Catches and handles format errors, such as invalid input, displaying an appropriate message.
      • General Exception: Catches and handles any other exceptions, providing a generic error message.
  3. Finally Block:
    • The finally block contains code that executes regardless of whether an exception is thrown. In this example, it prints a message indicating that the division operation has completed.

Key Concepts

  1. Exception Hierarchy:
    • All exceptions in C# derive from the base class System.Exception. Specific exceptions like DivideByZeroException and FormatException inherit from this class.
  2. Custom Exceptions:
    • You can create custom exceptions by deriving from the Exception class, allowing you to define your own error handling logic.
  3. Throwing Exceptions:
    • Use the throw keyword to explicitly throw an exception when a specific condition occurs.
  4. Exception Properties:
    • Exceptions have properties such as Message, StackTrace, and InnerException that provide detailed information about the error.

Best Practices

Catch Specific Exceptions: Always catch specific exceptions before catching the general Exception to provide more precise error handling.

Avoid Empty Catch Blocks: Avoid using empty catch blocks, as they can mask important errors and make debugging difficult.

Use Finally for Cleanup: Use the finally block to release resources, such as file handles or database connections, ensuring that resource cleanup occurs even if an exception is thrown.

Post a comment

Leave a Comment

Scroll to Top