VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/custom-exceptions-in-c/

⇱ Custom Exceptions in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Custom Exceptions in C#

Last Updated : 23 Apr, 2026

In C#, exceptions are used to handle unexpected situations in a program. The .NET Framework provides many built-in exception classes such as DivideByZeroException, NullReferenceException or IndexOutOfRangeException. However, sometimes predefined exceptions are not sufficient. In such cases, developers can create their own custom exceptions to represent specific error conditions.

What are Custom Exceptions?

Custom exceptions are user-defined exception classes created by inheriting from the base System.Exception class. They allow developers to:

  • Provide meaningful exception names.
  • Add custom messages.
  • Include additional properties for error details.

Steps to Create a Custom Exception

  1. Create a class that inherits from System.Exception.
  2. Provide one or more constructors (default, parameterized or with inner exceptions).
  3. (Optional) Add custom properties or methods to hold additional error information.

Example 1: Basic Custom Exception

Output:

Custom Exception Caught: Age must be 18 or above.

Explanation:

  • A custom exception InvalidAgeException is created.
  • When the condition fails, the custom exception is thrown and caught.

Example 2: Custom Exception with Additional Property

Output:

Insufficient balance. Current Balance: 500

Explanation:

  • AccountBalanceException has an extra property CurrentBalance to give detailed error information.
  • This helps in debugging and providing meaningful messages to users.

Key Points

  • Custom exceptions inherit from System.Exception.
  • They make error handling more specific and meaningful.
  • Additional details can be added using custom properties.
  • Custom exceptions should be used when built-in exceptions don’t clearly represent the error scenario.

Difference between Built-in and Custom Exceptions

Built-in ExceptionsCustom Exceptions
Provided by .NET Framework (e.g., NullReferenceException, IndexOutOfRangeException).Defined by the user for specific business rules or application needs.
General-purpose error handling.Represents domain-specific error conditions.
No extra properties beyond standard exception info.Can include additional fields and methods.
Comment
Article Tags:
Article Tags:

Explore