Ad space (banner)
โ˜•Java Lessons
Lesson 25 / 68

Writing a Custom Exception Class

This lesson covers writing your own exception class in Java, so you can express an error's category more specifically. It's for anyone searching "Java custom exception class tutorial."

Extending Exception lets you build your own "dedicated exception." Naming each exception class by category makes it easy to tell what went wrong when you catch it.

The example has a ValidationError class extend Exception, and a checkAge method โ€” declared with throws ValidationError โ€” throws the exception with throw new ValidationError(...) when the age is negative.

A common early mistake is forgetting the throws declaration. In Java, a method that throws a checked exception needs a throws declaration, and forgetting it produces a compile error.

In real projects, distinguishing between something like "an invalid input" exception and "a network failure" exception lets you write the appropriate response for each in code.

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

๐Ÿงช This site can't compile or run Java 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)