Custom Exceptions - potatoscript/csharp GitHub Wiki

⚑ Custom Exceptions in C# ⚑


πŸ₯” What is a Custom Exception?

In C#, when something goes wrong in your program, exceptions handle the problem and prevent the program from crashing. But sometimes, the default exceptions like FormatException, NullReferenceException, or IndexOutOfRangeException don’t give enough information. πŸ˜•

This is where custom exceptions come in! 🎁

βœ… A custom exception is an error that you define yourself.
βœ… You can give it a special name and write a custom error message.
βœ… It helps you handle specific situations that may not be covered by built-in exceptions.


🎯 Why Use Custom Exceptions?

  1. Specific Error Messages – Explain exactly what went wrong.
  2. Better Code Organization – Handle errors that are unique to your application.
  3. Easier Debugging – Makes it easier to track down problems when something goes wrong.

πŸ“š Example: Why Do We Need Custom Exceptions?

Imagine you’re making a Cookie Shop App where customers can buy cookies. πŸͺ But there’s a problem – if someone tries to buy more cookies than what’s available, you need to show a custom error.

Let’s see how to fix this with a custom exception!


πŸ“ How to Create a Custom Exception

Creating a custom exception is easy! You just:

  1. Create a new class that inherits from Exception.
  2. Add a constructor to pass the error message.
  3. Throw this exception when needed.

πŸ₯” Step 1: Basic Structure of Custom Exceptions

using System;

class CookieException : Exception
{
    // Constructor to pass the custom message
    public CookieException(string message) : base(message)
    {
    }
}

πŸ‘‰ Explanation:

  • CookieException is a new class that inherits from Exception.
  • The base(message) sends the error message to the parent Exception class.

πŸ₯” Step 2: Throwing a Custom Exception

You can throw a custom exception using throw just like normal exceptions.

using System;

class Program
{
    static void Main()
    {
        int availableCookies = 5;  // We have 5 cookies available

        try
        {
            Console.WriteLine("How many cookies do you want to buy?");
            int cookiesToBuy = int.Parse(Console.ReadLine());

            if (cookiesToBuy > availableCookies)
            {
                // Throw custom exception if cookies are not enough
                throw new CookieException("Not enough cookies available! πŸͺ");
            }
            else
            {
                Console.WriteLine("Enjoy your " + cookiesToBuy + " cookies! πŸͺ😊");
            }
        }
        catch (CookieException e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

🧠 Explanation:

  1. CookieException Class:

    • Created a class named CookieException that inherits from Exception.
    • Passes a custom error message when an error occurs.
  2. Main Program:

    • Asks how many cookies the user wants.
    • If they want more cookies than available, it throws the CookieException.
    • The catch block catches this custom error and displays the message.

🎁 Output:

βœ… If cookies are available:

How many cookies do you want to buy?
3
Enjoy your 3 cookies! πŸͺ😊

❌ If cookies are not enough:

How many cookies do you want to buy?
10
Error: Not enough cookies available! πŸͺ

πŸ₯” Step 3: Add More Features to Custom Exceptions

You can make your custom exceptions more powerful by adding extra information. For example, you can pass the number of available cookies to the exception.

πŸ₯” Improved CookieException with Extra Info

using System;

class CookieException : Exception
{
    public int AvailableCookies { get; }

    // Constructor with additional parameter
    public CookieException(string message, int availableCookies) : base(message)
    {
        AvailableCookies = availableCookies;
    }
}

πŸͺ Using the Improved CookieException

using System;

class Program
{
    static void Main()
    {
        int availableCookies = 5;

        try
        {
            Console.WriteLine("How many cookies do you want to buy?");
            int cookiesToBuy = int.Parse(Console.ReadLine());

            if (cookiesToBuy > availableCookies)
            {
                // Throw improved custom exception
                throw new CookieException($"Only {availableCookies} cookies available!", availableCookies);
            }
            else
            {
                Console.WriteLine("Enjoy your " + cookiesToBuy + " cookies! πŸͺ😊");
            }
        }
        catch (CookieException e)
        {
            Console.WriteLine("Error: " + e.Message);
            Console.WriteLine($"Hint: We have {e.AvailableCookies} cookies left! πŸͺ");
        }
    }
}

🎁 Output:

βœ… If cookies are available:

How many cookies do you want to buy?
3
Enjoy your 3 cookies! πŸͺ😊

❌ If cookies are not enough:

How many cookies do you want to buy?
10
Error: Only 5 cookies available!
Hint: We have 5 cookies left! πŸͺ

🚨 When to Use Custom Exceptions?

βœ… When built-in exceptions are not enough – If no existing exception matches your situation, create a custom one.
βœ… When you want to provide better error details – Add more info to help understand what went wrong.
βœ… When you have complex business logic – Custom exceptions help with custom business rules.


🎯 Best Practices for Custom Exceptions

  1. Inherit from Exception or ApplicationException – Always inherit from an appropriate base class.
  2. Add meaningful error messages – Make sure the message explains what went wrong.
  3. Include extra data if needed – Add properties or fields to hold useful info.
  4. Don’t overuse custom exceptions – Use them only when necessary.

🧠 Advanced: Multiple Custom Exceptions

You can create multiple custom exceptions for different situations.

🍩 Example: Cookie and Donut Exceptions

using System;

// Cookie Exception
class CookieException : Exception
{
    public CookieException(string message) : base(message)
    {
    }
}

// Donut Exception
class DonutException : Exception
{
    public DonutException(string message) : base(message)
    {
    }
}

πŸͺ Using Both Exceptions

using System;

class Program
{
    static void Main()
    {
        try
        {
            BuyCookies(10);  // Try to buy 10 cookies
            BuyDonuts(2);    // Try to buy 2 donuts
        }
        catch (CookieException e)
        {
            Console.WriteLine("Cookie Error: " + e.Message);
        }
        catch (DonutException e)
        {
            Console.WriteLine("Donut Error: " + e.Message);
        }
    }

    static void BuyCookies(int quantity)
    {
        int availableCookies = 5;

        if (quantity > availableCookies)
        {
            throw new CookieException("Not enough cookies available!");
        }
        Console.WriteLine("Enjoy your " + quantity + " cookies! πŸͺ");
    }

    static void BuyDonuts(int quantity)
    {
        int availableDonuts = 1;

        if (quantity > availableDonuts)
        {
            throw new DonutException("No donuts left!");
        }
        Console.WriteLine("Enjoy your " + quantity + " donuts! 🍩");
    }
}

🎁 Output:

❌ Trying to buy too many cookies:

Cookie Error: Not enough cookies available!