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 from System.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

ConceptDescription
throw new Exception()Manually raise a standard exception
throwRethrow caught exception preserving stack trace
Custom ExceptionCreate your own exception class by inheriting from Exception
PurposeSignal 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