In C#, the throw
keyword is a critical component for error handling, enabling the programmer to generate and manage exceptions intentionally. When an error or unexpected situation arises, throw
creates an exception object that can be caught and handled by the application’s logic. This tutorial will cover how and when to use the throw
keyword and including real-world examples.
throw
KeywordThe throw
keyword in C# is used to initiate an exception. It allows the program to signal that something unexpected has occurred, creating an exception object that details the issue and then halting the normal flow of execution. The throw
keyword can be used to rethrow exceptions, pass custom messages, and trigger specific exception types, making it highly flexible for various scenarios.
throw
Is EssentialThe throw
keyword is essential for:
throw
To use the throw
keyword, specify the exception type you wish to throw. Here’s a simple example of how to throw a generic Exception
in C#:
using System;
class Program
{
static void Main()
{
int age = -5;
if (age < 0)
{
throw new Exception("Age cannot be negative.");
}
}
}
In this example, if age is less than zero, the program throws an exception with the message "Age cannot be negative
".
Sometimes, you may catch an exception and rethrow it, allowing it to be handled elsewhere. Here’s an example:
try
{
int result = Divide(10, 0);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("An error occurred, rethrowing exception...");
throw; // Rethrows the original exception
}
int Divide(int a, int b)
{
return a / b;
}
Here, we catch a DivideByZeroException
and rethrow it using throw;, preserving the original stack trace, which is helpful for debugging.
The throw keyword is valuable for error handling in a variety of scenarios:
Consider a banking system where we need to validate the balance before allowing a withdrawal. We’ll use throw to signal issues like insufficient funds.
using System;
// Custom Exception for Insufficient Funds
public class InsufficientFundsException : Exception
{
public double AccountBalance { get; }
public InsufficientFundsException(double balance)
: base("Insufficient funds for the requested withdrawal.")
{
AccountBalance = balance;
}
}
// Bank Account Class Using `throw`
public class BankAccount
{
public double Balance { get; private set; }
public BankAccount(double initialBalance)
{
Balance = initialBalance;
}
public void Withdraw(double amount)
{
if (amount > Balance)
{
throw new InsufficientFundsException(Balance);
}
Balance -= amount;
Console.WriteLine($"Withdrawal of {amount} successful. New balance: {Balance}");
}
}
class Program
{
static void Main()
{
var account = new BankAccount(100);
try
{
account.Withdraw(150);
}
catch (InsufficientFundsException ex)
{
Console.WriteLine($"Error: {ex.Message}. Available balance is {ex.AccountBalance}.");
}
}
}
In this example:
InsufficientFundsException
: We create a custom exception to indicate insufficient funds.InsufficientFundsException
, stopping the withdrawal and alerting the user.This approach is a typical way to enforce business rules in applications and provide precise error handling.
throw
to signal specific errors, making it clear what went wrong.throw
is ideal for validation and enforcing rules within business logic.throw
; without an argument preserves the original stack trace, aiding debugging.The throw
keyword is a foundational feature in C# for error handling. By enabling developers to raise exceptions purposefully, throw ensures that programs handle errors effectively and recover gracefully where possible. It’s especially useful for validating inputs, enforcing business rules, and maintaining control over error handling flow. In our banking example, throw
allowed us to reject invalid withdrawals, enforcing important rules in a clear, structured way. With its flexibility and power, mastering throw equips you to build more reliable, maintainable applications.