Complete C# Tutorial

Top 15 Common Exception in C# with Examples and Try-Catch Solutions

🎯 Introduction

Ever been in the middle of coding when—bam!—your program crashes? 😱 It’s frustrating, especially when you have no idea why. But hey, you’re not alone! These unexpected hiccups are called exceptions, and C# has a powerful way to handle them: try-catch blocks.

In this friendly guide, you’ll explore the top 15 common exceptions in C# with easy-to-understand examples, real-life scenarios, and simple solutions. No boring jargon—just fun, relatable content to help you master exception handling. 😎

🛡️ Top 15 Common Exception in C# with Try-Catch Solutions

  1. NullReferenceException – Happens when you try to use an object that’s null.
  2. IndexOutOfRangeException – Occurs when you access an array or list element beyond its limit.
  3. DivideByZeroException – Raised when you divide a number by zero. 🚫
  4. FormatException – Thrown when data format isn’t correct (like converting letters to numbers).
  5. InvalidCastException – Happens when a conversion between incompatible data types is attempted.
  6. ArgumentException – Occurs when a method receives an invalid argument.
  7. ArgumentNullException – Raised when a null argument is passed where it shouldn’t be.
  8. ArgumentOutOfRangeException – Occurs when an argument is out of its valid range.
  9. OverflowException – Happens when arithmetic operations exceed the limit of the data type.
  10. StackOverflowException – Raised when there’s infinite recursion causing the stack to overflow.
  11. OutOfMemoryException – Occurs when the system runs out of memory (rare but possible!).
  12. IOException – Happens during input/output operations that fail (like file read errors).
  13. FileNotFoundException – Raised when a specified file can’t be found.
  14. KeyNotFoundException – Occurs when a key doesn’t exist in a dictionary.
  15. NotImplementedException – Thrown when a method hasn’t been implemented yet.

1️⃣ NullReferenceException – "Oops! Something’s Missing!"

This happens when you try to use an object that hasn’t been set (it’s null).

🔔 Real-World Example:

Imagine trying to call your friend 📞, but you don’t have their number saved. You’d get stuck, right? That’s exactly what happens when you reference something that doesn’t exist!

👉 Code Example:

				
					string name = null;
Console.WriteLine(name.Length); // 💥 Throws NullReferenceException
				
			

🖥️ Output:

				
					Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
				
			

Why it happens:

You’re trying to get the length of a null string. Since there’s nothing there, C# throws a fit! 😅

 

👉 How to fix it:

				
					try
{
    string name = null;
    Console.WriteLine(name.Length); // 💥 Throws NullReferenceException
}
catch (NullReferenceException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Object reference not set to an instance of an object.
				
			

🔍 Explanation:

The try block runs your code. If it runs into a null object, the catch block jumps in to handle the error. No crashing—just a friendly message! 😎

2️⃣ IndexOutOfRangeException – "Hey! That’s Out of Bounds!"

This happens when you access an array or list element that doesn’t exist.

🔔 Real-World Example:

Imagine ordering seat #10 in a 5-seat theater 🎬. Not gonna happen, right? Accessing an invalid array index works the same way.

👉 Code Example:

				
					int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // 💥 Throws IndexOutOfRangeException
				
			

🖥️ Output:

				
					Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
				
			

Why it happens:

You’re trying to access the 6th element in a 3-element array. C# won’t let that slide! 🚫

👉 How to fix it:

				
					try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]); // 💥 Throws IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Index was outside the bounds of the array.
				
			

🔍 Explanation:

The catch block saves the day by catching the error before it causes trouble! 🙌

3️⃣ DivideByZeroException – "Oops! Can’t Divide by Zero!"

This happens when you try to divide a number by zero.

🔔 Real-World Example:

Sharing pizza 🍕 with zero friends? Not possible! Same goes for division by zero in C#.

👉 Code Example:

				
					int x = 10;
int y = 0;
Console.WriteLine(x / y); // 💥 Throws DivideByZeroException
				
			

🖥️ Output:

				
					Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
				
			

Why it happens:

Dividing by zero is mathematically impossible, so C# throws this error.

👉 How to fix it:

				
					try
{
    int x = 10;
    int y = 0;
    Console.WriteLine(x / y); // 💥 Throws DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Attempted to divide by zero.
				
			

🔍 Explanation:

Always check for zero before dividing. Your code (and pizza) will thank you! 😄

4️⃣ FormatException – "Wait, That’s Not the Right Format!"

This happens when you try to convert something into the wrong format.

🔔 Real-World Example:

Entering letters instead of numbers at an ATM won’t work 🏦. Similarly, C# throws this error for invalid formats.

👉 Code Example:

				
					string input = "Hello";
int number = int.Parse(input); // 💥 Throws FormatException
				
			

🖥️ Output:

				
					Unhandled Exception: System.FormatException: Input string was not in a correct format.
				
			

Why it happens:

You can’t turn “Hello” into a number. C# just can’t do magic like that! 🎩🚫

👉 How to fix it:

				
					try
{
    string input = "Hello";
    int number = int.Parse(input); // 💥 Throws FormatException
}
catch (FormatException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Input string was not in a correct format.
				
			

🔍 Explanation:

Validate inputs before converting. Saves a lot of headaches! 😅

5️⃣ InvalidCastException – "Can’t Turn That Into This!"

This happens when you try to cast objects into incompatible types.

🔔 Real-World Example:

Trying to wear shoes on your hands? 🧤👟 Weird and just doesn’t work! Same goes for casting unrelated types.

👉 Code Example:

				
					object obj = "Steven";
int number = (int)obj; // 💥 Throws InvalidCastException
				
			

🖥️ Output:

				
					Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32'.
				
			

Why it happens:

You can’t turn a string into an integer directly. C# says nope! 🙅‍♂️

👉 How to fix it:

				
					try
{
    object obj = "Steven";
    int number = (int)obj; // 💥 Throws InvalidCastException
}
catch (InvalidCastException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Unable to cast object of type 'System.String' to type 'System.Int32'.
				
			

🔍 Explanation:

Use safe casting methods like as or is to avoid surprises. 😎

6️⃣ ArgumentException – "Wait! That Argument Looks Weird!"

This happens when you pass an invalid argument to a method.

🔔 Real-World Example:

Imagine ordering coffee ☕ with a flavor that doesn’t exist. The barista would be confused, right? That’s exactly what happens when you give a method an invalid argument!

👉 Code Example:

				
					string number = "abc";
int result = int.Parse(number); // 💥 Throws ArgumentException
				
			

🖥️ Output:

				
					Unhandled Exception: System.ArgumentException: Input string was not in a correct format.
				
			

Why it happens:

You’re trying to parse a non-numeric string into an integer. C# can’t convert "abc" into a number—so it throws a fit! 😅

👉 How to fix it:

				
					try
{
    string number = "abc";
    int result = int.Parse(number); // 💥 Throws ArgumentException
}
catch (ArgumentException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Input string was not in a correct format.
				
			

🔍 Explanation:

The try block attempts to parse the string. When it fails, the catch block handles the error gracefully. No crashes—just helpful feedback! 😎

7️⃣ ArgumentNullException – "Hey! You Forgot Something!"

This happens when you pass null to a method that doesn’t accept it.

🔔 Real-World Example:

Like handing a blank form 📝 to someone and expecting them to process it. Confusing, right? That’s what happens when you forget to provide a required value!

👉 Code Example:

				
					string text = null;
Console.WriteLine(text.ToUpper()); // 💥 Throws ArgumentNullException
				
			

🖥️ Output:

				
					Unhandled Exception: System.ArgumentNullException: Value cannot be null. (Parameter 'text')
				
			

Why it happens:

You’re trying to convert a null string to uppercase. Without a value, C# doesn’t know what to process! 🚫

👉 How to fix it:

				
					try
{
    string text = null;
    Console.WriteLine(text.ToUpper()); // 💥 Throws ArgumentNullException
}
catch (ArgumentNullException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Value cannot be null. (Parameter 'text')
				
			

🔍 Explanation:

The catch block saves the day, handling the null value so your program keeps running smoothly! 🦸‍♂️

8️⃣ ArgumentOutOfRangeException – "Whoa! That’s Too Far!"

This happens when you use a value outside the acceptable range.

🔔 Real-World Example:

Trying to book a hotel room 🏨 for -2 nights? Not possible! That’s what happens when you use an out-of-range value.

👉 Code Example:

				
					string name = "Steven";
Console.WriteLine(name.Substring(10)); // 💥 Throws ArgumentOutOfRangeException
				
			

🖥️ Output:

				
					Unhandled Exception: System.ArgumentOutOfRangeException: StartIndex cannot be larger than length of string. (Parameter 'startIndex')
				
			

Why it happens:

The Substring method expects a valid index. Since the string "Steven" is only 6 characters long, index 10 is way out of range! 🚫

👉 How to fix it:

				
					try
{
    string name = "Steven";
    Console.WriteLine(name.Substring(10)); // 💥 Throws ArgumentOutOfRangeException
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! StartIndex cannot be larger than length of string. (Parameter 'startIndex')
				
			

🔍 Explanation:

Using try-catch helps prevent unexpected crashes and provides a user-friendly error message. ✅

9️⃣ OverflowException – "Oops! That’s Too Big to Handle!"

This happens when a calculation exceeds the data type’s limit.

🔔 Real-World Example:

Filling a glass beyond its capacity 🥤—it spills over! The same thing happens when numbers go beyond their limits.

👉 Code Example:

				
					checked
{
    int max = int.MaxValue;
    int result = max + 1; // 💥 Throws OverflowException
}
				
			

🖥️ Output:

				
					Unhandled Exception: System.OverflowException: Arithmetic operation resulted in an overflow.
				
			

Why it happens:

int.MaxValue is the highest number an integer can hold. Adding 1 pushes it beyond that limit—boom! 💥

👉 How to fix it:

				
					try
{
    checked
    {
        int max = int.MaxValue;
        int result = max + 1; // 💥 Throws OverflowException
    }
}
catch (OverflowException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Arithmetic operation resulted in an overflow.
				
			

🔍 Explanation:

The checked keyword detects overflows. Pair it with try-catch to handle issues safely! 🛡️

🔟 StackOverflowException – "Too Much Recursion!"

This happens when methods call themselves infinitely.

🔔 Real-World Example:

Looking into two mirrors facing each other 🪞—endless reflections! Infinite recursion works the same way.

👉 Code Example:

				
					void RecursiveMethod() => RecursiveMethod(); // 💥 Infinite recursion
RecursiveMethod();
				
			

🖥️ Output:

				
					Unhandled Exception: System.StackOverflowException
				
			

Why it happens:

There’s no stopping condition in the recursive call, causing the stack to overflow! 😵

👉 How to fix it:

				
					try
{
    RecursiveMethod();
}
catch (StackOverflowException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}

void RecursiveMethod()
{
    // Add a base condition to avoid infinite recursion
    Console.WriteLine("Base case reached!");
}
				
			

💡 Output:

				
					Oops! Process is terminated due to StackOverflowException.
				
			

🔍 Explanation:

Always include a base condition in recursive methods to prevent infinite loops. 🔁✅

1️⃣1️⃣ OutOfMemoryException – "Out of Space! 😬"

This happens when there isn’t enough memory for an operation.

🔔 Real-World Example:

Trying to fit a giant couch into a tiny room 🛋️—no chance! That’s how C# feels when memory runs out.

👉 Code Example:

				
					int[] hugeArray = new int[int.MaxValue]; // 💥 Throws OutOfMemoryException
				
			

🖥️ Output:

				
					Unhandled Exception: System.OutOfMemoryException: Array dimensions exceeded supported range.
				
			

Why it happens:

You’re trying to create an array that’s way too large. The system simply can’t handle it! 🚫

👉 How to fix it:

				
					try
{
    int[] hugeArray = new int[int.MaxValue]; // 💥 Throws OutOfMemoryException
}
catch (OutOfMemoryException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Array dimensions exceeded supported range.
				
			

🔍 Explanation:

Plan your memory usage wisely and avoid creating massive data structures. 🧠💡

1️⃣2️⃣ IOException – "Uh-oh! File Trouble!"

This happens when something goes wrong with input/output operations.

🔔 Real-World Example:

Trying to open a locked door without a key 🗝️—no luck! File issues work similarly.

👉 Code Example:

				
					using var reader = new StreamReader("nonexistent.txt"); // 💥 Throws IOException
Console.WriteLine(reader.ReadToEnd());
				
			

🖥️ Output:

				
					Unhandled Exception: System.IO.IOException: Could not find file 'nonexistent.txt'.
				
			

Why it happens:

The file you’re trying to read doesn’t exist. C# can’t find what’s not there! 📂❓

👉 How to fix it:

				
					try
{
    using var reader = new StreamReader("nonexistent.txt"); // 💥 Throws IOException
    Console.WriteLine(reader.ReadToEnd());
}
catch (IOException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Could not find file 'nonexistent.txt'.
				
			

🔍 Explanation:

Always check if files exist before accessing them. 🗂️✔️

1️⃣3️⃣ FileNotFoundException – "Where’s That File?"

This happens when a file can’t be found at the specified path.

🔔 Real-World Example:

Searching for your keys 🔑 in an empty drawer—frustrating, right?

👉 Code Example:

				
					File.ReadAllText("missingFile.txt"); // 💥 Throws FileNotFoundException
				
			

🖥️ Output:

				
					Unhandled Exception: System.IO.FileNotFoundException: Could not find file 'missingFile.txt'.
				
			

Why it happens:

C# is looking for a file that doesn’t exist at the given location. 🚫

👉 How to fix it:

				
					try
{
    File.ReadAllText("missingFile.txt"); // 💥 Throws FileNotFoundException
}
catch (FileNotFoundException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! Could not find file 'missingFile.txt'.
				
			

🔍 Explanation:

Verify file paths and names to prevent this error. 🗂️✅

1️⃣4️⃣ KeyNotFoundException – "Oops! That Key Doesn’t Exist!"

This happens when you access a dictionary with a non-existent key.

🔔 Real-World Example:

Trying to open a locker with the wrong key 🔒—nope!

👉 Code Example:

				
					var myDictionary = new Dictionary<string, int>();
Console.WriteLine(myDictionary["age"]); // 💥 Throws KeyNotFoundException
				
			

🖥️ Output:

				
					Unhandled Exception: System.Collections.Generic.KeyNotFoundException: The given key 'age' was not present in the dictionary.
				
			

Why it happens:

You’re accessing a key that doesn’t exist. C# can’t find what’s not there! 🚪❓

👉 How to fix it:

				
					try
{
    var myDictionary = new Dictionary<string, int>();
    Console.WriteLine(myDictionary["age"]); // 💥 Throws KeyNotFoundException
}
catch (KeyNotFoundException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}
				
			

💡 Output:

				
					Oops! The given key 'age' was not present in the dictionary.
				
			

🔍 Explanation:

Check if the key exists using ContainsKey() before accessing it. 🗝️✅

1️⃣5️⃣ NotImplementedException – "Not Ready Yet! 🚧"

This happens when you call a method that hasn’t been implemented.

🔔 Real-World Example:

Seeing a “Coming Soon” sign 🏗️ at your favorite restaurant. No food yet! 🍔⏳

👉 Code Example:

				
					void NotReadyMethod()
{
    throw new NotImplementedException("This feature is coming soon!"); // 💥 Throws NotImplementedException
}

NotReadyMethod();
				
			

🖥️ Output:

				
					Unhandled Exception: System.NotImplementedException: This feature is coming soon!
				
			

Why it happens:

You’re calling a method that’s just a placeholder—no code inside! 🚧

👉 How to fix it:

				
					try
{
    NotReadyMethod();
}
catch (NotImplementedException ex)
{
    Console.WriteLine($"Oops! {ex.Message}");
}

void NotReadyMethod()
{
    throw new NotImplementedException("This feature is coming soon!");
}
				
			

💡 Output:

				
					Oops! This feature is coming soon!
				
			

🔍 Explanation:

Make sure to implement methods before calling them. 🚀✅

🏆 Conclusion

Exceptions happen to the best of us, but with try-catch, you’re fully equipped to handle them like a coding superhero! 🦸‍♀️💻 Keep practicing, stay curious, and never be afraid to make mistakes—they’re just stepping stones to becoming awesome! 🙌

 

🚀 Next What?

Woohoo! 🎉 You just learned how to handle the top 10 Common Exception in C# with ease! Feeling more confident? I bet you are! 😎

👉 Coming up next: We’ll dive into Try Catch Finally in C# and discover how to clean up resources like a pro. Don’t miss it! 🚀

 

Let me know if you got stuck anywhere or need more examples. I’m here to help! 😊

Leave a Comment

Share this Doc

Common Exceptions

Or copy link