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?
- Specific Error Messages β Explain exactly what went wrong.
- Better Code Organization β Handle errors that are unique to your application.
- 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:
- Create a new class that inherits from
Exception
. - Add a constructor to pass the error message.
- 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 fromException
.- The
base(message)
sends the error message to the parentException
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:
-
CookieException Class:
- Created a class named
CookieException
that inherits fromException
. - Passes a custom error message when an error occurs.
- Created a class named
-
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
- Inherit from
Exception
orApplicationException
β Always inherit from an appropriate base class. - Add meaningful error messages β Make sure the message explains what went wrong.
- Include extra data if needed β Add properties or fields to hold useful info.
- 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!