Throw Keyword in C#
What is the Throw Keyword in C#?
The throw keyword in C# is used to generate an exception manually. It is commonly used in exception handling to signal an error condition and transfer control to a catch
block.
Key Features of the Throw Keyword
- Explicitly raises an exception.
- Can be used inside a
catch
block to rethrow an exception. - Allows custom exceptions to be thrown for better error handling.
- Stops the execution of the current method and jumps to the nearest exception handler.
Example: Throwing a Built-in Exception
The following example demonstrates how to use throw
to raise a DivideByZeroException
.
Example: Throwing a Built-in Exception
using System;
class Program
{
static void Main()
{
try
{
int num1 = 10, num2 = 0;
if (num2 == 0)
{
throw new DivideByZeroException("Cannot divide by zero.");
}
int result = num1 / num2;
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Exception Caught: {ex.Message}");
}
}
}
// Output:
// Exception Caught: Cannot divide by zero.
The throw
statement manually raises a DivideByZeroException
when the denominator is zero.
Throwing Custom Exceptions
You can create and throw custom exceptions by inheriting from the Exception
class.
Example: Throwing a Custom Exception
using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(string message) : base(message) { }
}
class Program
{
static void Main()
{
try
{
int age = 15;
if (age < 18)
{
throw new InvalidAgeException("Age must be 18 or older.");
}
Console.WriteLine("Age is valid.");
}
catch (InvalidAgeException ex)
{
Console.WriteLine($"Custom Exception Caught: {ex.Message}");
}
}
}
// Output:
// Custom Exception Caught: Age must be 18 or older.
This example demonstrates how to create a InvalidAgeException
and use the throw
keyword to raise it.
Rethrowing an Exception
The throw
keyword can be used inside a catch
block to rethrow an exception to a higher-level handler.
Example: Rethrowing an Exception
using System;
class Program
{
static void Main()
{
try
{
ProcessData();
}
catch (Exception ex)
{
Console.WriteLine($"Exception Handled in Main: {ex.Message}");
}
}
static void ProcessData()
{
try
{
throw new InvalidOperationException("Invalid operation detected.");
}
catch (InvalidOperationException)
{
Console.WriteLine("Logging exception...");
throw; // Rethrow the exception
}
}
}
// Output:
// Logging exception...
// Exception Handled in Main: Invalid operation detected.
Here, the throw
statement inside the catch
block propagates the exception to the outer try
block.
Best Practices for Using the Throw Keyword
- Use
throw
for custom validation and error handling. - Avoid throwing exceptions for normal control flow; use return values or flags instead.
- Always include meaningful error messages in custom exceptions.
- Use
throw;
(without parameters) to preserve the original stack trace when rethrowing exceptions.