0
0
C Sharp (C#)programming~5 mins

Custom exception classes in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Custom exception classes let you create your own error types to better explain problems in your program.
When you want to clearly show a specific problem in your code.
When built-in errors are too general and don't explain the issue well.
When you want to catch and handle a special error differently.
When you want to add extra information to an error.
When you want your program to be easier to understand and fix.
Syntax
C Sharp (C#)
public class MyCustomException : Exception
{
    public MyCustomException() { }
    public MyCustomException(string message) : base(message) { }
    public MyCustomException(string message, Exception inner) : base(message, inner) { }
}
Your custom exception class should inherit from the built-in Exception class.
You can add constructors to pass messages or inner exceptions.
Examples
A simple custom exception that takes a message.
C Sharp (C#)
public class AgeException : Exception
{
    public AgeException(string message) : base(message) { }
}
Custom exception with extra information about the missing file.
C Sharp (C#)
public class FileMissingException : Exception
{
    public string FileName { get; }
    public FileMissingException(string fileName) : base($"File {fileName} is missing.")
    {
        FileName = fileName;
    }
}
Sample Program
This program defines a custom exception called AgeException. It checks if age is less than 18 and throws the custom error. The error is caught and its message is printed.
C Sharp (C#)
using System;

public class AgeException : Exception
{
    public AgeException(string message) : base(message) { }
}

class Program
{
    static void CheckAge(int age)
    {
        if (age < 18)
        {
            throw new AgeException("Age must be at least 18.");
        }
        Console.WriteLine("Age is valid.");
    }

    static void Main()
    {
        try
        {
            CheckAge(15);
        }
        catch (AgeException ex)
        {
            Console.WriteLine($"Custom error caught: {ex.Message}");
        }
    }
}
OutputSuccess
Important Notes
Always inherit from Exception or a subclass of it when creating custom exceptions.
Use meaningful names for your custom exceptions to make your code easier to read.
You can add extra properties or methods to your custom exception if you want to store more details.
Summary
Custom exceptions help explain specific problems clearly.
Create them by inheriting from Exception and adding constructors.
Use them to catch and handle special errors in your program.