Complete C# Tutorial

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 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-in Exception class.
  • base(message): Passes your custom message to the base Exception 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! ๐ŸŽ‰๐Ÿ”ฅ

Leave a Comment

Share this Doc

User defined exception

Or copy link