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…

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers 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

  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.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help