Complete C# Tutorial

Using checked and unchecked with Try-Catch in C#: Explained with Examples

Hey buddy! 😃 Have you ever wondered how checked and unchecked work with try-catch blocks in C#? Well, you’re in the right place! 🙌 Today, you’ll learn how to use these keywords to handle arithmetic overflows—without getting confused. Plus, I’ll throw in some fun examples and real-life scenarios! 🎯

Why Do You Need checked and unchecked with Try-Catch?

Imagine you’re coding a shopping cart 🛒. You add up the prices, and—boom!—you hit a number too big for an integer. Without proper handling, your app might show crazy numbers! 😱

Here’s where checked (to catch errors) and unchecked (to skip checks) come in handy—especially when wrapped in a try-catch block to handle exceptions gracefully. 🙌

📝 Syntax

				
					try
{
    checked
    {
        // Code that checks for arithmetic overflow
    }
}
catch (OverflowException ex)
{
    Console.WriteLine("Exception caught: " + ex.Message);
}

try
{
    unchecked
    {
        // Code that ignores overflow
    }
}
catch (Exception ex)
{
    Console.WriteLine("Exception caught: " + ex.Message); // Usually won’t catch overflow here
}
				
			

💻 Example 1: checked Inside Try-Catch (Safe and Secure)

				
					using System;

class Program
{
    static void Main()
    {
        try
        {
            int max = int.MaxValue;
            int result = checked(max + 1);  // This will throw an exception
            Console.WriteLine("Result: " + result);
        }
        catch (OverflowException ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
    }
}
				
			

🔍 Output:

				
					Exception caught: Arithmetic operation resulted in an overflow.
				
			

👉 Explanation:

  • What’s happening? You’re trying to add 1 to the largest possible integer (int.MaxValue).
  • Why the exception? Because checked forces C# to notice the overflow.
  • Why use try-catch? It helps you handle the error without crashing the program. 🛡️

💡 Real-world scenario: Imagine adding reward points in a loyalty app. If someone magically earns too many points, you’d want to catch that issue, right? 😅

💻 Example 2: unchecked Inside Try-Catch (Risky Business)

				
					using System;

class Program
{
    static void Main()
    {
        try
        {
            int max = int.MaxValue;
            int result = unchecked(max + 1);  // Overflow is ignored
            Console.WriteLine("Result: " + result);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);  // Won’t be triggered
        }
    }
}
				
			

🔍 Output:

				
					Result: -2147483648
				
			

👉 Explanation:

  • Why no exception? Because unchecked tells C# to ignore the overflow.
  • Result? The value wraps around to the negative side (which can cause sneaky bugs! 😬).

💡 When to use? In performance-critical code where speed matters more than safety (but be careful!).

💻 Example 3: Combining checked and unchecked (Best of Both Worlds)

				
					using System;

class Program
{
    static void Main()
    {
        try
        {
            int safeResult = checked(100 + 50);  // No overflow, safe addition
            Console.WriteLine("Safe Result: " + safeResult);

            int riskyResult = unchecked(int.MaxValue + 1);  // Overflow ignored
            Console.WriteLine("Risky Result: " + riskyResult);
        }
        catch (OverflowException ex)
        {
            Console.WriteLine("Exception caught: " + ex.Message);
        }
    }
}
				
			

🔍 Output:

				
					Safe Result: 150
Risky Result: -2147483648
				
			

👉 Explanation:

  • First calculation: No overflow, so checked is happy! 😊
  • Second calculation: unchecked lets the overflow slide, giving a weird negative number.

🌍 Real-World Scenario: Budget Calculator

Imagine you’re building a budget calculator 💵. If someone inputs insanely large expenses, you’d want to catch the overflow using checked. Otherwise, your app might show crazy negative balances! 😲

				
					using System;

class BudgetCalculator
{
    static void Main()
    {
        try
        {
            int budget = 2000000000;
            int expenses = 1000000000;

            int total = checked(budget + expenses);  // Might overflow
            Console.WriteLine("Total Budget: " + total);
        }
        catch (OverflowException)
        {
            Console.WriteLine("Oops! The total budget is too large to handle. 🛑");
        }
    }
}
				
			

🔍 Output:

				
					Oops! The total budget is too large to handle. 🛑
				
			

👉 Why this matters: No one wants to see a negative budget in a financial app! 😅

🥳 Conclusion:

Use checked when you need safety.
⚠️ Use unchecked when you’re okay with risky overflows.
💡 Wrap them in try-catch to handle errors gracefully.

Remember, buddy: better safe than sorry! 😉 Your users will thank you for error-free apps! 🙌

 

🚀 Next What?

Awesome work! 🙌 You just learned how to use checked and unchecked statements with exception handling. Not too tricky, right? 😎 Up next, we’re diving into something super useful—file handling in C#! 📄✨ Get ready to learn how to read, write, and manage files like a pro. Can’t wait to see you there! 🚀🎉

Leave a Comment

Share this Doc

Checked and unchecked statements

Or copy link