Sobes.tech
Junior

What is the throw operator in C#?

sobes.tech AI

Answer from AI

The throw operator is used to explicitly initiate an exception. It allows interrupting the normal execution of the program and transferring control to the exception handling block.

// Example of using the throw operator
try
{
    int[] numbers = { 1, 2, 3 };
    int index = 5;

    // Manually initiating an IndexOutOfRangeException
    if (index >= numbers.Length)
    {
        throw new IndexOutOfRangeException("Index is out of bounds.");
    }

    Console.WriteLine(numbers[index]);
}
catch (IndexOutOfRangeException ex)
{
    // Handling the exception
    Console.WriteLine($"Error: {ex.Message}");
}

The throw operator can be used in two forms:

  1. throw expression;: Initiates a new exception, where expression is an instance of a class derived from System.Exception.

    throw new ArgumentException("Invalid argument.");
    
  2. throw;: Rethrows the current exception in a catch block. This preserves the full stack trace of the original exception.

    try
    {
        // Code that may throw an exception
    }
    catch (FileNotFoundException ex)
    {
        // Additional handling or logging
        Console.WriteLine($"File not found: {ex.FileName}");
    
        // Rethrow the exception for further handling up the stack
        throw;
    }
    

Using throw is important for:

  • Indicating errors or unexpected situations in the application.
  • Creating custom exceptions for specific errors.
  • Passing error information to the calling code for proper handling.