User Defined Exception in C# - Create Custom Exceptions Easily
๐ฏ Introduction
Imagine Emma managing a library system. ๐ She wants to make sure no one borrows more than 5 books at a time. What if someone tries to borrow 10? Emma needs a special alert for that. Unfortunately, built-in exceptions donโt cover such specific rules. Thatโs when user defined exceptions in C# come to the rescue! ๐ฆธโโ๏ธ
Sometimes, your program faces problems that standard exceptions just canโt describe. In such cases, creating your own custom exceptions lets you handle those situations with style and precision. Cool, right? ๐ Letโs explore how you can be the boss of your errors!
๐ What You Are Going to Learn in This Lesson
โ๏ธ What is a user defined exception in C#?
โ๏ธ Why and when should you use custom exceptions?
โ๏ธ How to create and throw your own exceptions.
โ๏ธ Real-world examples with complete code and outputs.
โ๏ธ Fun and interactive explanations to make learning easy! ๐
๐ What is a User Defined Exception in C#?
A user defined exception in C# (also called a C# custom exception) is a special error you create to handle situations not covered by built-in exceptions.
Think of it like this: You know your program better than anyone. If you see a specific condition that should raise a red flag, you create your own exception! ๐ฉ
๐ฅ๏ธ Syntax to Create a User Defined Exception
Hereโs how you define your custom exception:
public class MyCustomException : Exception
{
public MyCustomException(string message) : base(message)
{
}
}
๐ก Explanation:
MyCustomException
: Name of your custom exception class.: Exception
: Inherits from the built-inException
class.base(message)
: Passes your custom message to the baseException
class.
๐ ๏ธ Example 1: Simple Custom Exception
โ Scenario: Oliver wants a program that stops users from entering negative ages.
using System;
public class NegativeAgeException : Exception
{
public NegativeAgeException(string message) : base(message) { }
}
public class Program
{
public static void Main()
{
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
if (age < 0)
throw new NegativeAgeException("Age cannot be negative!");
Console.WriteLine($"Your age is {age}.");
}
}
๐จ๏ธ Output:
Enter your age: -5
Unhandled exception. NegativeAgeException: Age cannot be negative!
๐ Explanation:
When the user enters -5
, the code throws NegativeAgeException
. Without it, the program wouldnโt alert the user in a friendly way. This shows how helpful custom exceptions are! ๐
๐ ๏ธ Example 2: Real World Scenario - Bank Withdrawal System
โ Scenario:Sophia wants her banking app to block withdrawals beyond the account balance.
using System;
public class InsufficientBalanceException : Exception
{
public InsufficientBalanceException(string message) : base(message) { }
}
public class BankAccount
{
public double Balance { get; private set; }
public BankAccount(double balance) => Balance = balance;
public void Withdraw(double amount)
{
if (amount > Balance)
throw new InsufficientBalanceException("Insufficient balance!");
Balance -= amount;
Console.WriteLine($"Withdrawal successful! New balance: ${Balance}");
}
}
public class Program
{
public static void Main()
{
BankAccount account = new BankAccount(1000);
Console.WriteLine($"Current balance: ${account.Balance}");
Console.Write("Enter withdrawal amount: ");
double amount = double.Parse(Console.ReadLine());
account.Withdraw(amount);
}
}
๐จ๏ธ Output:
Current balance: $1000
Enter withdrawal amount: 1500
Unhandled exception. InsufficientBalanceException: Insufficient balance!
๐ Explanation:
When the user tries to withdraw $1500
, the InsufficientBalanceException
is triggered. Without this check, users could overdraw their accounts. ๐ซ๐ธ
๐ ๏ธ Example 3: Student Grade Validation
โ Scenario:Noah wants to ensure grades are between 0 and 100.
using System;
public class InvalidGradeException : Exception
{
public InvalidGradeException(string message) : base(message) { }
}
public class Student
{
public void SetGrade(int grade)
{
if (grade < 0 || grade > 100)
throw new InvalidGradeException("Grade must be between 0 and 100.");
Console.WriteLine($"Grade set to: {grade}");
}
}
public class Program
{
public static void Main()
{
Student student = new Student();
Console.Write("Enter student grade: ");
int grade = int.Parse(Console.ReadLine());
student.SetGrade(grade);
}
}
๐จ๏ธ Output:
Enter student grade: 105
Unhandled exception. InvalidGradeException: Grade must be between 0 and 100.
๐ Explanation:
Grades like 105
arenโt valid. Noahโs custom exception makes sure no such mistakes slip through! ๐โ
๐ ๏ธ Example 4: Parking Lot Capacity Check
โ Scenario:Liam manages a parking lot with a max capacity of 50 cars. No more should enter when full.
using System;
public class ParkingFullException : Exception
{
public ParkingFullException(string message) : base(message) { }
}
public class ParkingLot
{
public int Capacity { get; }
public int CarsParked { get; private set; }
public ParkingLot(int capacity) => Capacity = capacity;
public void ParkCar()
{
if (CarsParked >= Capacity)
throw new ParkingFullException("Parking lot is full!");
CarsParked++;
Console.WriteLine($"Car parked! Total cars: {CarsParked}");
}
}
public class Program
{
public static void Main()
{
ParkingLot lot = new ParkingLot(2);
try
{
lot.ParkCar(); // 1st car
lot.ParkCar(); // 2nd car
lot.ParkCar(); // 3rd car throws exception
}
catch (ParkingFullException ex)
{
Console.WriteLine(ex.Message);
}
}
}
๐จ๏ธ Output:
Car parked! Total cars: 1
Car parked! Total cars: 2
Parking lot is full!
๐ Explanation:
When the third car tries to park, the ParkingFullException
prevents overcrowding. ๐
ฟ๏ธ๐๐ซ
๐ Conclusion
Youโve just unlocked the power of user defined exceptions in C#! ๐ Creating custom exceptions allows you to handle unique problems with clarity. Whether it’s controlling library books, managing bank withdrawals, or preventing parking chaos, you’re now ready to make your programs smarter and safer. ๐ก๏ธ
ย
๐ Next what?
Excited to take your exception-handling skills further? ๐ In the next chapter, youโll learn about nested & multiple catch in C#. Itโs like having multiple safety nets for different types of errors! Stay tunedโyour C# journey just keeps getting better! ๐๐ฅ