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
MediumCreate a custom exception class named InvalidTemperatureException that inherits from Exception. It should have:
- A default constructor that sets a message "Temperature is not valid."
- 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
InvalidTemperatureExceptionwith the message "Temperature below absolute zero!" if the temperature is less than -273 - Returns true if the temperature is valid
Cheat sheet
To create a custom exception, define a class that inherits from Exception:
public class InvalidAgeException : Exception
{
public InvalidAgeException() : base("Age is not valid.")
{
}
public InvalidAgeException(string message) : base(message)
{
}
}Throw your custom exception when needed:
int age = -5;
if (age < 0)
{
throw new InvalidAgeException("Age cannot be negative.");
}Try it yourself
using System;
class CheckTemperature
{
// Create your custom exception class here
public static bool checkTemperature(int celsius)
{
// Write your code here
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety