Exception Handling in C# with Examples and Easy Explanation
🎯 Introduction
Ever had your computer freeze or an app suddenly crash? 😩 Annoying, right? Imagine writing a program and bam!—it crashes when the user enters something unexpected. This is where Exception Handling in C# comes to the rescue! 🚀
Think of it like seatbelts in cars. You don’t plan to crash, but if you do, seatbelts protect you. Likewise, exception handling saves your program from crashing when things go wrong.
📘 What You Are Going to Learn in This Lesson:
✔️ What is Exception in C#
✔️ Simple programs that raise exceptions
📝 What is Exception in C#?
In simple words, an exception is an error that happens when your program runs. Like trying to divide a number by zero or opening a file that doesn’t exist. Without handling it, your program might just crash. 😬
Exception Handling in C# helps you catch these errors, handle them gracefully, and keep your program running smoothly. You can show friendly messages instead of confusing error codes.
Exception examples
Sometimes your code will misbehave in ways you didn’t expect. 🙈 These examples will show you what can go wrong and how exceptions pop up.
💻 Example 1: Divide By Zero Exception
Steven wants to share candies, but what if there are no friends to share with? 🍬❌
using System;
class Program
{
static void Main()
{
int candies = 10;
int friends = 0; // Oops! No friends
int candiesPerFriend = candies / friends; // Raises exception
Console.WriteLine($"Each friend gets {candiesPerFriend} candies.");
}
}
🖥️ Output:
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
👉 Why This Happens:
You can’t divide by zero—C# stops and shouts, “Hey, that’s not allowed!” 😱
💻 Example 2: Null Reference Exception
Steven tries to send a message but forgets to write one. What happens?
using System;
class Program
{
static void Main()
{
string message = null; // No message written
Console.WriteLine(message.Length); // Raises exception
}
}
🖥️ Output:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
👉 Why This Happens:
You can’t check the length of nothing! It’s like trying to count the pages of an empty book. 📖❌
💻 Example 3: Index Out Of Range Exception
Steven has 3 pets but tries to name a fourth one. 🐶🐱🐰… Wait, what fourth pet?
using System;
class Program
{
static void Main()
{
string[] pets = { "Dog", "Cat", "Rabbit" };
Console.WriteLine(pets[3]); // There's no pet at index 3!
}
}
🖥️ Output:
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
👉 Why This Happens:
Arrays start at index 0, so pets[3]
doesn’t exist! It’s like looking for a seat that’s not there. 🪑❌
💻 Example 4: File Not Found Exception
Steven wants to read a file that doesn’t exist. Let’s see the code:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "missingFile.txt"; // File doesn't exist
string content = File.ReadAllText(filePath); // Raises exception
Console.WriteLine(content);
}
}
🖥️ Output:
Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'missingFile.txt'.
👉 Why This Happens:
You can’t read what isn’t there! It’s like opening an empty mailbox hoping for letters. 📬❌
How to Handle Exception in C#?
Oops! 😬 Exceptions can really mess things up, can’t they? One moment your program is running smoothly, and the next—boom! It crashes unexpectedly.
But don’t worry! 😊 There’s a way to stop your program from breaking when things go wrong. In C#, you can handle exceptions and make sure your program stays calm even when something unexpected happens.
Sounds cool, right? 😎 You might be wondering how to do that.
Well, hold tight! In the next lesson, I’ll walk you through the steps to handle exceptions one by one. It’s easier than you think, and you’ll have fun learning it. Stay tuned! 🚀
🚀 Next what?
Awesome job, my friend! 🎉 You’ve just learned what an exception is and now have a solid understanding of it. Feels good, right? 😎 But wait, there’s more! In the next chapter, you’ll dive into common exceptions in C# that pop up in everyday coding.
💡 You will learn 15 of the most common and popular exceptions along with their solutions. This will help you avoid those annoying surprises and handle errors like a pro! 😅
So, are you ready to level up your coding game? Let’s jump into the next chapter together! 🚀