0
0
CsharpHow-ToBeginner · 3 min read

How to Create Custom Exception in C# - Simple Guide

To create a custom exception in C#, define a new class that inherits from Exception and implement constructors to pass messages or inner exceptions. This lets you throw and catch your own specific error types for clearer error handling.
📐

Syntax

Define a class that inherits from Exception. Implement constructors to initialize the exception with a message and optionally an inner exception.

  • Class name: Your custom exception name.
  • Base class: Exception or a subclass.
  • Constructors: Default, message, and message with inner exception.
csharp
public class MyCustomException : Exception
{
    public MyCustomException() { }

    public MyCustomException(string message) : base(message) { }

    public MyCustomException(string message, Exception inner) : base(message, inner) { }
}
💻

Example

This example shows how to create and throw a custom exception, then catch it to display the error message.

csharp
using System;

public class MyCustomException : Exception
{
    public MyCustomException() { }

    public MyCustomException(string message) : base(message) { }

    public MyCustomException(string message, Exception inner) : base(message, inner) { }
}

class Program
{
    static void Main()
    {
        try
        {
            throw new MyCustomException("Something went wrong in the app.");
        }
        catch (MyCustomException ex)
        {
            Console.WriteLine($"Caught custom exception: {ex.Message}");
        }
    }
}
Output
Caught custom exception: Something went wrong in the app.
⚠️

Common Pitfalls

Common mistakes when creating custom exceptions include:

  • Not inheriting from Exception or a subclass, which breaks exception behavior.
  • Omitting constructors, making it hard to pass error messages.
  • Not calling the base constructor, which can lose important exception data.

Always implement constructors that call the base class to keep standard exception features.

csharp
/* Wrong: Missing base constructor call */
public class BadException : Exception
{
    public BadException(string message) { /* missing base(message) */ }
}

/* Right: Calls base constructor properly */
public class GoodException : Exception
{
    public GoodException(string message) : base(message) { }
}
📊

Quick Reference

Remember these tips when creating custom exceptions:

  • Always inherit from Exception.
  • Implement constructors that call base constructors.
  • Use meaningful exception names ending with "Exception".
  • Throw your custom exception where specific error handling is needed.

Key Takeaways

Create a custom exception by inheriting from the Exception class.
Implement constructors that call the base Exception constructors.
Use your custom exception to provide clear, specific error messages.
Always name your exception classes ending with 'Exception' for clarity.
Catch your custom exceptions to handle specific error cases gracefully.