Menu
Coddy logo textTech

Custom Exceptions

Part of the Logic & Flow section of Coddy's C# journey. Lesson 29 of 66.

Custom exceptions allow you to create specific exception types for your application's unique error scenarios.

To create a custom exception, define a class that inherits from Exception. Inheritance means your new class automatically gains all the behavior of the parent class, in this case, Exception, while letting you add or customize functionality. The syntax class MyException : Exception means MyException extends Exception.

public class InvalidAgeException : Exception
{
    public InvalidAgeException() : base("Age is not valid.")
    {
    }
    
    public InvalidAgeException(string message) : base(message)
    {
    }
}

: Exception: inherits from the built-in Exception class.
: base(...): calls the parent Exception constructor to set the error message.
The first constructor provides a default message when none is supplied.
The second constructor accepts a custom message so callers can describe the error in detail.

Now you can throw your custom exception when needed:

int age = -5;
if (age < 0)
{
    throw new InvalidAgeException("Age cannot be negative.");
}

When this code executes with a negative age, it will throw your custom exception with the message "Age cannot be negative."

Note: In the exercises for this lesson, validation functions return true when the input is valid and throw a custom exception when it is not. Because an unhandled exception stops execution immediately, the test cases only need to verify the true return path: the exception itself is the observable result for invalid inputs.

challenge icon

Challenge

Medium

Create a custom exception class named InvalidTemperatureException that inherits from Exception. It should have:

  1. A default constructor that sets a message "Temperature is not valid."
  2. A constructor that accepts a custom message.

Then implement a method named checkTemperature that:

  • Takes an integer parameter representing a temperature in Celsius
  • Throws an InvalidTemperatureException with the message "Temperature below absolute zero!" if the temperature is less than -273
  • Returns true if the temperature is valid

Try it yourself

using System;

class CheckTemperature
{
    // Create your custom exception class here
    
    public static bool checkTemperature(int celsius)
    {
        // Write your code here
    }
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online C# compiler