C# Custom Exceptions: Complete Guide [2023]

By Josip Miskovic
A thumbnail showing C# exceptions code.

Create a custom exception in C#

In C#, you can create custom exceptions by creating a new class that derives from the Exception class. The custom exception class can also have additional properties or methods that you need.

Here is an example of how you could create a custom exception class in C#:

C#
public class InvalidInputException : Exception
{
    public InvalidInputException() : base() { }
    public InvalidInputException(string message) : base(message) { }
    public InvalidInputException(string message, Exception innerException) : base(message, innerException) { }
}

This custom exception class above represents a condition where the user has provided invalid input. The class derives from the built-in Exception class and adds a few additional constructors to make it easier to create the exception.

Here is an example of how to throw and catch this custom exception:

C#
try
{
    // code that might throw an exception
    if (inputIsInvalid)
    {
        throw new InvalidInputException("The input is invalid!");
    }
}
catch (InvalidInputException ex)
{
    // handle the exception
    Console.WriteLine(ex.Message);
}

In this example, the try block contains code that might throw an InvalidInputException if the input is invalid. If the exception is thrown, it is caught in the catch block and the error message is printed to the console.

Visual Studio and Visual Studio Code have shortcuts that help you create custom exceptions.

Custom Exceptions Best Practices

Here are a few things to keep in mind when creating custom exceptions in C#:

  1. Create a separate exception class for each error condition that you want to handle. This makes it easier to identify and handle specific exceptions in your code.

  2. Override the Message property to provide a meaningful error message that describes the error condition. This message will be displayed when the exception is thrown.

  3. Override the ToString() method to return a string representation of the exception, which can be useful for logging and debugging purposes.

  4. Add additional properties or methods that you need to your custom exception class to provide more information about the error condition.

What to avoid when creating custom exceptions in C#?

Here are a few things to avoid when working with custom exceptions in C#:

  1. Avoid creating too many custom exception classes. It is a good idea to create a separate exception class for each error condition that you want to handle, but you should try to keep the number of exception classes to a minimum. Having too many exception classes can make your code more difficult to understand and maintain.

  2. Avoid throwing exceptions for expected error conditions. Exceptions are intended to handle unexpected error conditions, not to control the normal flow of your code. If you have an error condition that you expect to occur under certain circumstances, it is better to handle it using normal control flow statements like if and else rather than throwing an exception.

  3. Avoid catching and ignoring exceptions. If you catch an exception, you should take some action to handle the error condition. Ignoring exceptions can cause problems in your code and make it difficult to track down and fix bugs.

  4. Avoid catching the base Exception class. The Exception class is the base class for all exceptions in C#, and catching this class will catch all exceptions, including those that you might not be prepared to handle. Instead, you should catch specific exception types that you are prepared to handle.

Custom Exception Performance

Using custom exceptions in C# should not have a significant impact on the performance of your code. Throwing and catching exceptions can be somewhat slower than normal control flow statements like if and else, but the difference is usually small and should not be a concern unless you are writing code that needs to be extremely high performance.

In general, the benefits of using custom exceptions far outweigh any potential performance issues. Custom exceptions can help you write more organized and maintainable code by providing a clear and concise way to represent and handle error conditions.

Custom Exception examples

Custom exception class with custom properties

Here is an example of a custom exception class that includes custom properties:

C#
public class InvalidInputException : Exception
{
    public string InvalidInput { get; }

    public InvalidInputException(string message, string invalidInput) : base(message)
    {
        InvalidInput = invalidInput;
    }
}

This custom exception class represents an error condition where the user has provided invalid input. The class includes a custom property called InvalidInput that stores the invalid input that caused the exception.

Here is an example of how you could throw and catch this custom exception:

C#
try
{
    // code that might throw an exception
    if (inputIsInvalid)
    {
        throw new InvalidInputException("The input is invalid!", invalidInput);
    }
}
catch (InvalidInputException ex)
{
    // handle the exception
    Console.WriteLine(ex.Message);
    Console.WriteLine("Invalid input: " + ex.InvalidInput);
}

In this example, the try block contains code that might throw an InvalidInputException if the input is invalid. If the exception is thrown, it is caught in the catch block and the error message and invalid input are printed to the console.

Most important terms

Here is a table of some important terms related to custom exceptions in C#:

Term Definition
Exception

The base class for all exceptions in C#. The Exception class provides properties and methods for handling exceptions, such as the Message property for storing an error message and the StackTrace property for storing a stack trace.

Throw

The throw keyword is used to throw an exception. When an exception is thrown, the current method is terminated and the exception is passed up the call stack until it is caught by a catch block.

Catch

The catch keyword is used to catch an exception that has been thrown. The catch block specifies a type parameter that indicates the type of exception to catch and a variable that will receive the exception object. The catch block can contain code to handle the exception.

Try-catch block

A try-catch block is used to handle exceptions in C#. The try block contains code that might throw an exception, and the catch block contains code to handle the exception if it is thrown. Multiple catch blocks can be used to handle different types of exceptions.

Custom exception

A custom exception is a class that derives from the Exception class and represents a specific error condition. Custom exceptions can be created by adding additional properties and methods to the exception class to provide more information about the error condition.

Finally block

The finally block is an optional block that can be used with a try-catch block. The code in the finally block is always executed, regardless of whether an exception is thrown or caught. The finally block is typically used to clean up resources, such as closing file handles or database connections.

FAQ: Custom Exceptions

Here are a few frequently asked questions about custom exceptions in C#:

When should I create a custom exception class?

It is generally a good idea to create a custom exception class when you want to represent a specific error condition that is not covered by the built-in exception classes in C#. For example, if you are working on a financial application, you might want to create a custom exception class to represent an error condition where the user has insufficient funds in their account.

How do I throw a custom exception?

To throw a custom exception, you can create an instance of your custom exception class and use the throw keyword to throw it. For example:

C#
throw new InvalidInputException("The input is invalid!");

How do I catch a custom exception?

To catch a custom exception, you can use a catch block with a type parameter that matches the type of your custom exception class. For example:

C#
try
{
    // code that might throw an exception
}
catch (InvalidInputException ex)
{
    // handle the exception
}

Can I add additional properties or methods to my custom exception class?

Yes, you can add any additional properties or methods that you need to your custom exception class. This can be useful if you want to provide more information about the error condition. For example, you might want to add a property to store the invalid input that caused the exception, or a method to log the exception to a file.

What are the `base()` calls in custom exceptions?

In C#, the base keyword is used to access the base class of a derived class. When creating a custom exception class that derives from the built-in Exception class, you can use the base keyword to call the constructors of the base class.

For example, consider the following custom exception class:

C#
public class InvalidInputException : Exception
{
    public InvalidInputException() : base() { }
    public InvalidInputException(string message) : base(message) { }
    public InvalidInputException(string message, Exception innerException) : base(message, innerException) { }
}

This custom exception class has three constructors, each of which calls the corresponding constructor of the Exception class using the base keyword.

The first constructor calls the default constructor of the Exception class, the second constructor calls the Exception constructor that takes a message parameter, and the third constructor calls the Exception constructor that takes a message and inner exception parameter.

The base() calls in the custom exception class allow the class to inherit the behavior and functionality of the Exception class, while also adding any additional properties or methods that are specific to the custom exception class.

Published on:
Josip Miskovic
About Josip

Josip Miskovic is a software developer at Americaneagle.com. Josip has 10+ years in experience in developing web applications, mobile apps, and games.

Read more posts →
Download Free Software Developer Career Guide

I've used these principles to increase my earnings by 63% in two years. So can you.

Dive into my 7 actionable steps to elevate your career.