Custom Exception

What is a custom exception?

What is a custom exception? A custom exception, in the context of programming, refers to an exception that you define yourself, rather than using one of the built-in exceptions provided by the programming language or framework. Custom exceptions are tailored to specific scenarios or error conditions within your application or domain.

Custom Exception in C#:

In C#, creating a custom exception involves defining a new class that inherits from the System.Exception class or one of its derived classes. Here's a step-by-step guide on how to create a custom exception in C#:

1. Create a new class: Define a new class for your custom exception. Typically, you would derive this class from 'System.Exception'.

2. Add constructors: Implement constructors to initialize the exception with appropriate messages and optionally include inner exceptions.

3. Customize properties and methods: Optionally, you can add custom properties and methods to your exception class to provide additional information about the error.

Demonstrating of a custom exception:

cs Copy Code
using System;

// Custom exception class
public class CustExcep : Exception
{
    // Constructors
    public CustExcep() : base() { }

    public CustExcep(string msg) : base(msg) { }

    public CustExcep(string msg, Exception inExc) : base(msg, inExc) { }

    // You can add additional properties or methods if needed
    public int ErrorCode { get; set; }
}

// Example usage
class Program
{
    static void Main(string[] args)
    {
        try
        {
            // Simulating an error condition
            throw new CustExcep("This is a custom exception.");
        }
        catch (CustExcep ex)
        {
            Console.WriteLine("Custom Exception Caught: " + ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Generic Exception Caught: " + ex.Message);
        }
    }
}

Explanation:

We define a custom exception class MyCustomException that inherits from 'System.Exception'.

We provide constructors to allow initializing the exception with a message and optionally with an inner exception.

We demonstrate throwing and catching the custom exception in the 'Main' method.

Output:
Custom Exception Caught: This is a custom exception.

Note: Custom exceptions in C# can be used to handle specific error conditions in your application, providing meaningful error messages and additional context to facilitate debugging and error recovery.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.