codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🔷

C# Programming

29 / 60 topics
27Exceptions in C#28Try-Catch-Finally Blocks29Custom Exceptions in C#
Tutorials/C# Programming/Custom Exceptions in C#
🔷C# Programming

Custom Exceptions in C#

Updated 2026-05-15
10 min read

Custom Exceptions in C#

Introduction

In the world of programming, handling errors gracefully is crucial for building robust applications. C# provides a powerful mechanism to handle exceptions through its exception handling model. While .NET offers a wide range of built-in exceptions, sometimes you need to define your own custom exceptions to better suit the specific needs of your application.

Custom exceptions allow you to create more meaningful error messages and handle errors in a way that is specific to your application's context. In this tutorial, we will explore how to create and use custom exceptions in C#.

Concept

An exception in C# is an object that describes an error or unusual condition that has occurred during the execution of a program. When an error occurs, an exception is thrown, and if not handled properly, it can terminate your application. Custom exceptions are user-defined classes that inherit from the base Exception class.

To create a custom exception, you need to define a new class that inherits from Exception. You can also override properties like Message or add additional properties to provide more context about the error.

Examples

Let's walk through creating and using a custom exception in C# with some practical examples.

Step 1: Define a Custom Exception Class

First, we need to define a new class that inherits from Exception. Let's create a custom exception called InvalidAgeException which will be used to handle errors related to invalid age inputs.

csharp
1public class InvalidAgeException : Exception
2{
3 public int Age { get; }
4
5 public InvalidAgeException(int age, string message) : base(message)
6 {
7 Age = age;
8 }
9}

In this example, we have added an additional property Age to store the invalid age value. The constructor takes both the age and a custom error message.

Step 2: Using the Custom Exception

Now that we have our custom exception defined, let's see how to use it in a method that validates user input for age.

csharp
1public class AgeValidator
2{
3 public void ValidateAge(int age)
4 {
5 if (age < 0 || age > 120)
6 {
7 throw new InvalidAgeException(age, "Age must be between 0 and 120.");
8 }
9 }
10}

In the ValidateAge method, we check if the provided age is within a valid range (0 to 120). If not, we throw an InvalidAgeException.

Step 3: Handling the Custom Exception

To handle the custom exception, you can use a try-catch block. Let's see how this works in practice.

csharp
1public class Program
2{
3 public static void Main()
4 {
5 AgeValidator validator = new AgeValidator();
6
7 try
8 {
9 Console.Write("Enter your age: ");
10 int age = int.Parse(Console.ReadLine());
11 validator.ValidateAge(age);
12 Console.WriteLine("Age is valid.");
13 }
14 catch (InvalidAgeException ex)
15 {
16 Console.WriteLine($"Error: {ex.Message}");
17 Console.WriteLine($"Invalid Age: {ex.Age}");
18 }
19 }
20}

In this example, we prompt the user to enter their age and then call ValidateAge. If an InvalidAgeException is thrown, it is caught in the catch block where we print the error message and the invalid age.

Output

Let's see what happens when you run this program:

Terminal
$ dotnet run
Enter your age: 150
Error: Age must be between 0 and 120.
Invalid Age: 150
Output
Enter your age: 150
Error: Age must be between 0 and 120.
Invalid Age: 150

As you can see, the custom exception provides a clear and specific error message along with the invalid age value.

What's Next?

Now that you have learned how to create and use custom exceptions in C#, you might want to explore other aspects of error handling such as file I/O operations. Understanding how to handle files safely is essential for many applications, so make sure to check out our next tutorial on "File I/O Operations in C#".

By mastering custom exceptions and other error handling techniques, you will be well-equipped to build more resilient and user-friendly applications.

Info

Remember, custom exceptions should be used judiciously. Only define them when they provide meaningful information that enhances the error handling process.


PreviousTry-Catch-Finally BlocksNext File I/O Operations in C#

Recommended Gear

Try-Catch-Finally BlocksFile I/O Operations in C#