Letβs go through throwing exceptions using throw
in C# β an important part of error handling.
π 1. What is throw
?
-
The
throw
keyword is used to manually raise an exception -
Signals that an error or unexpected condition has occurred
-
Can be caught using try-catch
π 2. Basic Syntax
throw new ExceptionType("Error message");
-
ExceptionType
β any class derived fromSystem.Exception
-
"Error message"
β descriptive message about the error
π 3. Example: Throwing a Standard Exception
void ValidateAge(int age)
{
if (age < 0)
throw new ArgumentException("Age cannot be negative");
}
try
{
ValidateAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine("Caught an exception: " + ex.Message);
}
Output:
Caught an exception: Age cannot be negative
π 4. Rethrowing an Exception
- Sometimes you want to catch an exception, do something, then rethrow
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Logging error: " + ex.Message);
throw; // Rethrow same exception
}
-
throw;
preserves the original stack trace -
Donβt use
throw ex;
if you want to keep the original stack trace intact
π 5. Throwing Custom Exceptions
- You can define your own exception class by inheriting from
Exception
public class NegativeAgeException : Exception
{
public NegativeAgeException(string message) : base(message) { }
}
void ValidateAge(int age)
{
if (age < 0)
throw new NegativeAgeException("Age cannot be negative!");
}
try
{
ValidateAge(-1);
}
catch (NegativeAgeException ex)
{
Console.WriteLine(ex.Message);
}
Output:
Age cannot be negative!
π 6. Summary Table
Concept | Description |
---|---|
throw new Exception() | Manually raise a standard exception |
throw | Rethrow caught exception preserving stack trace |
Custom Exception | Create your own exception class by inheriting from Exception |
Purpose | Signal errors, enforce validation, control flow in exceptional situations |
β Tips:
-
Use specific exception types instead of generic
Exception
-
Include clear error messages
-
Use
throw
to stop execution when an invalid state is detected