Try Catch Finally - potatoscript/csharp GitHub Wiki

⚑ Try-Catch-Finally in C# ⚑


πŸ₯” What is Try-Catch-Finally? πŸ₯”

In C#, when we write code, sometimes things go wrong! πŸ’₯ Imagine you’re trying to open a cookie jar, but oh no! The lid is stuck! 😱 You try again and again, but it won’t open. Finally, you get help and solve the problem. πŸͺ

In programming, this is where Try-Catch-Finally comes in.

  • try – You try to do something (like open the cookie jar).
  • catch – If something goes wrong, you catch the error and handle it.
  • finally – No matter what happens, this part always runs at the end.

🎯 Why Do We Need Try-Catch-Finally?

  1. Prevents crashes – Stops the program from breaking when errors occur.
  2. Handles errors gracefully – Gives you control over what to do when something goes wrong.
  3. Ensures cleanup – The finally block helps clean up resources, like closing a file or database connection.

πŸ“ Basic Structure of Try-Catch-Finally

Here’s how it looks:

try
{
    // Try to do something risky
}
catch (Exception e)
{
    // Handle the error here
}
finally
{
    // This code always runs, no matter what happens
}

πŸ“š Example: Try-Catch-Finally with Explanation

πŸ“– Story Time: Max and the Cookie Jar

Max loves cookies, and he tries to open the cookie jar. But sometimes, the jar gets stuck! πŸ₯΄
Let’s see how we can write this in C#:

using System;

class Program
{
    static void Main()
    {
        try
        {
            // Max tries to open the cookie jar
            Console.WriteLine("Max is trying to open the cookie jar...");
            
            // Oh no! An error happens (simulate an error)
            throw new Exception("The lid is stuck!");
        }
        catch (Exception e)
        {
            // Max handles the error
            Console.WriteLine("Oops! Something went wrong: " + e.Message);
        }
        finally
        {
            // Max cleans up (like putting the jar back)
            Console.WriteLine("Max puts the cookie jar back safely.");
        }
    }
}

🧠 Explanation:

  1. try Block:

    • Max tries to open the cookie jar.
    • But something goes wrong (throw new Exception), and an error occurs.
  2. catch Block:

    • Max catches the error and shows the message:
      πŸ—£οΈ β€œOops! Something went wrong: The lid is stuck!”
  3. finally Block:

    • No matter what happens, Max always puts the jar back at the end.

🚨 What Happens When No Error Occurs?

If no error happens, the catch block is skipped but the finally block still runs.

πŸ₯” Example: No Error in the Cookie Jar

using System;

class Program
{
    static void Main()
    {
        try
        {
            // No error this time
            Console.WriteLine("Max opens the cookie jar successfully!");
        }
        catch (Exception e)
        {
            Console.WriteLine("Oops! Something went wrong: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Max puts the cookie jar back safely.");
        }
    }
}

πŸ‘‰ Output:

Max opens the cookie jar successfully!
Max puts the cookie jar back safely.

πŸ”₯ Multiple Catch Blocks: Catching Different Errors

Sometimes, different errors can happen, and we might need to handle them differently.

πŸ₯” Example: Handling Multiple Errors

using System;

class Program
{
    static void Main()
    {
        try
        {
            Console.WriteLine("Enter a number:");
            int number = int.Parse(Console.ReadLine());  // Try to convert user input
        }
        catch (FormatException)
        {
            // Handles format errors (e.g., user types letters instead of numbers)
            Console.WriteLine("Oops! Please enter a valid number.");
        }
        catch (OverflowException)
        {
            // Handles very large numbers
            Console.WriteLine("The number is too big!");
        }
        catch (Exception e)
        {
            // Handles any other unexpected errors
            Console.WriteLine("Something went wrong: " + e.Message);
        }
        finally
        {
            Console.WriteLine("Program finished.");
        }
    }
}

πŸ‘‰ Possible Outputs:

Enter a number:
abc
Oops! Please enter a valid number.
Program finished.
Enter a number:
999999999999999999
The number is too big!
Program finished.

🧹 Using finally to Clean Up Resources

The finally block is great when you need to release resources (like closing a file or database connection).

πŸ₯” Example: Closing a File Properly

using System;
using System.IO;

class Program
{
    static void Main()
    {
        StreamReader file = null;

        try
        {
            // Try to open and read the file
            file = new StreamReader("potato.txt");
            string content = file.ReadToEnd();
            Console.WriteLine(content);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("File not found! Please check the file name.");
        }
        finally
        {
            // Close the file to release resources
            if (file != null)
            {
                file.Close();
                Console.WriteLine("File is closed.");
            }
        }
    }
}

πŸ”₯ Advanced: Throwing Custom Exceptions

Sometimes, we want to create our own errors when something specific goes wrong. You can use throw to raise an error.

πŸ₯” Example: Throwing Custom Error

using System;

class Program
{
    static void Main()
    {
        try
        {
            int cookies = 0;

            if (cookies == 0)
            {
                // Throw custom error if no cookies are left
                throw new Exception("No cookies left! πŸͺ");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Oops! " + e.Message);
        }
        finally
        {
            Console.WriteLine("Max cleans up the kitchen.");
        }
    }
}

πŸ‘‰ Output:

Oops! No cookies left! πŸͺ
Max cleans up the kitchen.