Creating Custom Exceptions

Tutorial 4 of 5

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

  1. Exercise 1: Create a NegativeNumberException that is thrown when a negative number is used where it shouldn't be.
  2. Exercise 2: Create an InvalidEmailException that 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.