Throw Statement in C# - Learn How to Throw Exceptions Easily
🎯 Introduction
Ever wished you could warn your program before something goes wrong? Imagine Steven lending books to friends. If a friend asks for zero books, shouldn’t he raise an alert? 📢 That’s where the throw statement in C# comes in! It’s like saying, “Hey, something’s wrong—stop and fix it!” 🚦
Sometimes, your code knows there’s a problem before C# does. Instead of waiting for an automatic exception, you can throw your own. Pretty cool, right? 😎 Stick with me, and you’ll be a pro in no time!
📚 What You Are Going to Learn in This Lesson
✔️ What is the throw statement in C#?
✔️ Why and when should you use it?
✔️ How to use it with simple syntax and examples.
✔️ Real-world scenarios to make it relatable.
✔️ 3 to 4 clear programming examples with outputs and explanations.
Ready to take control? Let’s dive in! 🌊
🧩 What is the Throw Statement in C#?
The throw statement in C# lets you intentionally raise an exception. Think of it like a fire alarm. 🚨 If something’s off, you can alert the system before things get worse.
You might use it when:
✅ Input values are invalid.
✅ A method is used incorrectly.
✅ You want to pass the problem to higher-level code.
📝 Syntax:
throw new ExceptionType("Your custom error message");
👉 Replace ExceptionType
with a valid exception like ArgumentException
, InvalidOperationException
, or even a custom one.
Simple enough, right? Let’s check out some real examples! 🚀
💻 Example 1: Basic Throw Statement in C#
Steven wants to buy candies but hates negative numbers. Let’s help him out:
using System;
class Program
{
static void BuyCandies(int quantity)
{
if (quantity < 0)
throw new ArgumentException("Quantity can't be negative! ❌");
Console.WriteLine($"Buying {quantity} candies. 🍬");
}
static void Main()
{
try
{
BuyCandies(-5); // Risky input!
}
catch (ArgumentException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
🖥️ Output:
Error: Quantity can't be negative! ❌
👉 Explanation:
- The
BuyCandies
method checks ifquantity
is negative. - If it is, it throws an
ArgumentException
with a custom message. - The
catch
block handles it and shows a friendly error message.
Easy peasy, right? 🍭
💻 Example 2: Real-World Scenario - Bank Withdrawal 🏦
Steven tries to withdraw money. What if he requests more than his balance? Let’s handle that:
using System;
class BankAccount
{
public int Balance { get; set; }
public BankAccount(int initialBalance)
{
Balance = initialBalance;
}
public void Withdraw(int amount)
{
if (amount > Balance)
throw new InvalidOperationException("Insufficient balance! 💸");
Balance -= amount;
Console.WriteLine($"Withdrawal successful! New balance: ${Balance}");
}
}
class Program
{
static void Main()
{
var account = new BankAccount(100);
try
{
account.Withdraw(150); // Too much!
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
🖥️ Output:
Error: Insufficient balance! 💸
👉 Explanation:
- If the withdrawal exceeds the balance, an exception is thrown.
- The program warns Steven instead of going negative.
- No hidden surprises—just clear, friendly feedback! 😊
💻 Example 3: Throwing Exceptions in Methods 🚀
Steven divides numbers but wants to avoid zero as the divisor. Let’s make it safe:
using System;
class Calculator
{
public static int Divide(int a, int b)
{
if (b == 0)
throw new DivideByZeroException("Can't divide by zero! 🧨");
return a / b;
}
}
class Program
{
static void Main()
{
try
{
int result = Calculator.Divide(10, 0); // Risky!
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
🖥️ Output:
Error: Can't divide by zero! 🧨
👉 Explanation:
- The
Divide
method checks for zero divisors. - Instead of crashing, it throws an exception with a clear message.
- Steven stays safe, and you learn a valuable lesson! 😄
💻 Example 4: Re-throwing Exceptions 🔄
What if you want to catch an error but pass it along? Let’s see:
using System;
class Program
{
static void ValidateName(string name)
{
try
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Name can't be empty! ✋");
}
catch (ArgumentException ex)
{
Console.WriteLine($"Caught inside method: {ex.Message}");
throw; // Re-throwing the exception
}
}
static void Main()
{
try
{
ValidateName(""); // Empty name!
}
catch (Exception ex)
{
Console.WriteLine($"Caught in Main: {ex.Message}");
}
}
}
🖥️ Output:
Caught inside method: Name can't be empty! ✋
Caught in Main: Name can't be empty! ✋
👉 Explanation:
- The method catches the error but re-throws it for higher-level handling.
- This helps when you want to log the error but still let the main program know.
- Steven gets double protection—just like you should in coding! 😎
🏆 Why Use the Throw Statement in C#?
👉 Catch issues before they become bigger problems.
👉 Provide clear, friendly error messages.
👉 Make your code safer and easier to debug.
👉 Keep users (and Steven) happy with helpful feedback! 😃
📝 Conclusion
Wow, you’ve come so far! 🎉 The throw statement in C# gives you the power to spot problems and alert your program before it crashes. No more surprises—just clean, controlled code. 💪 So, how do you feel? Pretty awesome, right? I knew you’d rock this! 😎
🚀 Next what?
Ready to level up? In the next chapter, you’ll learn how to create your own custom exceptions using user-defined exceptions in C#. Imagine designing your own warning signs for your code! 🚦 Stay tuned—it’s going to be a blast! 🎊