C# Interview Question #53

What is a custom exception in C#?

Exceptions, Delegates, Events & Lambdas Mid-Level Intermediate

Quick Interview Answer

A custom exception is an application-specific exception type, normally derived from Exception. It can represent a meaningful business or domain failure that built-in exception types do not describe clearly.

Detailed Explanation

A custom exception is an application-specific exception type, normally derived from Exception. It can represent a meaningful business or domain failure that built-in exception types do not describe clearly.

Custom exceptions should be used selectively. Creating a unique exception for every possible error usually adds unnecessary complexity.

A custom exception can carry a clear message and preserve an inner exception when wrapping a lower-level failure.

Code Example

public class ProductNotFoundException : Exception
{
    public ProductNotFoundException(int id)
        : base($"Product with ID {id} was not found.")
    {
    }
}