C# / Exception Handling in C#
Creating Custom Exceptions
In this tutorial, we'll explore how to create custom exceptions in C#. Custom exceptions are user-defined error types that provide more context about the error, making it easier t…
Section overview
5 resourcesCovers exception handling techniques for error management in C#.
1. Introduction
In this tutorial, we'll learn how to create and use custom exceptions in C#. Exceptions are unexpected or exceptional runtime conditions that disrupt the normal flow of the program. Custom exceptions, as the name suggests, are user-defined exceptions allowing us to create more meaningful and specific error messages.
Goals
By the end of the tutorial, you will:
- Understand what custom exceptions are and why they are important.
- Learn how to create and use custom exceptions in your C# code.
Prerequisites
You should have a basic understanding of C#, including classes and exceptions. If not, you might want to check out some introductory tutorials first.
2. Step-by-Step Guide
In C#, exceptions are instances of classes that derive from the base class Exception. To create a custom exception, we will create a new class that inherits from Exception or one of its subclasses.
Creating a Custom Exception
Here's a simple example of a custom exception named InvalidAgeException:
public class InvalidAgeException : Exception
{
public InvalidAgeException() : base("Invalid age. Age should be non-negative.")
{
}
}
In this example, we've created a new class InvalidAgeException that extends the Exception class. The constructor calls the base class constructor with a specific error message.
Throwing a Custom Exception
Throwing a custom exception is the same as throwing a built-in exception. Here's an example:
public void SetAge(int age)
{
if (age < 0)
{
throw new InvalidAgeException();
}
// remaining code...
}
3. Code Examples
Let's look at a more complex example with additional properties in the exception class.
public class InvalidAgeException : Exception
{
public int Age { get; }
public InvalidAgeException(int age) : base("Invalid age. Age should be non-negative.")
{
Age = age;
}
public override string ToString()
{
return $"{Message}\nInvalid Value: {Age}";
}
}
In this version of InvalidAgeException, we have added an Age property that holds the invalid age value. We have also overridden the ToString method to include the invalid age in the error message.
Here's an example of using this exception:
public void SetAge(int age)
{
if (age < 0)
{
throw new InvalidAgeException(age);
}
// remaining code...
}
4. Summary
In this tutorial, we learned how to create and use custom exceptions in C#. Custom exceptions enhance the standard exception handling in C# by providing more specific, meaningful error messages.
Next, you can explore how to handle these custom exceptions using try-catch blocks, and how to define multiple custom exceptions for different error conditions.
5. Practice Exercises
- Exercise 1: Create a
NegativeNumberExceptionthat is thrown when a negative number is used where it shouldn't be. - Exercise 2: Create an
InvalidEmailExceptionthat is thrown when an email address doesn't have a valid format.
Solution 1:
public class NegativeNumberException : Exception
{
public NegativeNumberException() : base("Negative numbers are not allowed here.")
{
}
}
Solution 2:
public class InvalidEmailException : Exception
{
public InvalidEmailException() : base("Invalid email address.")
{
}
}
Practice more by using these exceptions in your code when appropriate conditions are met.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article