Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 25 / 68

Writing a Custom Exception Class

In this lesson you will learn how to define your own exception class in C#, so you can describe error conditions more precisely. This is for anyone searching for "C# custom exception class how to create".

Inheriting from Exception gives you an exception of your own. Naming a class per kind of failure makes it much easier to tell what went wrong when you catch it.

The sample code has ValidationError inherit from Exception and raises it with throw new ValidationError(...) inside CheckAge when the age is negative. catch (ValidationError e) then catches only that kind of exception.

A common stumbling block for beginners is sticking with the built-in Exception and losing the ability to tell error types apart. Once you can distinguish "invalid input" from "network failure", you can write a response suited to each.

In real-world development, giving an exception an InnerException lets it carry the details of the original underlying failure along with it.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)