C# Throw Example: Handle Errors Like a Pro!
Ever had your program crash out of nowhere? Annoying, right? 😫 What if I told you that you could take control of errors instead of letting them ruin your day? That’s where throw statements come in!
In this lesson, we’ll break down the C# throw statement with a real-world example, complete code, and step-by-step explanation. So, let’s make errors work for us instead of against us! 😃
What You Are Going to Learn in This Lesson
✔️ What is a throw statement in C#?
✔️ How does it work with exceptions?
✔️ A real-world example with complete code & output
✔️ Why and when to use it?
✔️ A friendly summary + what’s next 🚀
Sounds exciting? Let’s go! 🎯
Introduction: What is a Throw Statement in C#?
In simple words, a throw statement is used to intentionally create an error (exception) in your program. Instead of letting C# crash randomly, you tell it when and how to fail.
For example:
throw new Exception("Oops! Something went wrong!");
This line stops the program and displays the error message. But why would you want that? Well, sometimes, you need to validate input or prevent serious mistakes.
Let’s see how it works in real life!
Real-World Scenario: ATM Withdrawal System 🏧
Imagine you’re using an ATM. You enter an amount, but what if it’s more than your balance? Instead of giving you money you don’t have (which would be awesome but illegal! 😂), the system throws an error and stops the transaction.
Let’s write a C# Throw Example for this! 🚀
C# Throw Example: ATM Withdrawal
💻 Code Example:
using System;
class Program
{
static void WithdrawMoney(double balance, double amount)
{
if (amount > balance)
{
throw new Exception("Insufficient balance! You can’t withdraw more than what you have.");
}
balance -= amount;
Console.WriteLine($"Withdrawal successful! Your new balance is: ${balance}");
}
static void Main()
{
try
{
double myBalance = 500.00;
Console.WriteLine($"Current Balance: ${myBalance}");
Console.Write("Enter amount to withdraw: ");
double withdrawAmount = Convert.ToDouble(Console.ReadLine());
WithdrawMoney(myBalance, withdrawAmount);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Output 1 (Valid Withdrawal)
Current Balance: $500
Enter amount to withdraw: 200
Withdrawal successful! Your new balance is: $300
Output 2 (Invalid Withdrawal – More Than Balance)
Current Balance: $500
Enter amount to withdraw: 600
Error: Insufficient balance! You can’t withdraw more than what you have.
Breaking Down the Code 🧐
Let’s go step by step so that you fully understand this.
1️⃣ WithdrawMoney() Method
- It checks if the withdrawal amount is greater than the balance.
- If yes, it throws an error (
throw new Exception(...)
). - Otherwise, it deducts the amount and prints the new balance.
2️⃣ Main() Method
- Asks the user to enter an amount.
- Calls
WithdrawMoney()
with the given amount. - If an error happens, the catch block catches it and displays a friendly message instead of crashing.
Why Use Throw Statements? 🤔
- Prevents bad input (e.g., withdrawing more than your balance).
- Gives meaningful error messages instead of random crashes.
- Stops the program from doing something it shouldn’t (like giving out free money! 💸😂).
- Makes debugging easier because errors are controlled.
Conclusion:
See? C# throw statements aren’t scary at all! They help you handle problems smoothly instead of letting your program go crazy. You’ve just learned:
✔️ What a throw statement is.
✔️ How it prevents bad actions (like overdrawing money).
✔️ How to write and use throw in C#.
✔️ A real-world ATM example with output.
So, next time your program misbehaves, throw some errors like a pro! 😃
Next What? 🚀
In the next lesson, you’ll learn about Checked & Unchecked Statements in C#. These are super useful for handling integer overflows and unexpected calculations. It’s gonna be fun—so stay tuned! 😃
💡 If you have difficulty or a question, drop a comment. We’ll be happy to help you! 😊