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:
-
throw expression;: Initiates a new exception, whereexpressionis an instance of a class derived fromSystem.Exception.throw new ArgumentException("Invalid argument."); -
throw;: Rethrows the current exception in acatchblock. 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.