Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 25 / 68

Creating your own exception type

This lesson covers defining your own exception type in Julia, with the aim of expressing kinds of error more specifically.

A struct that inherits from Exception gives you an exception of your own. Separating the types by kind of error makes it much easier to tell what went wrong when you catch it.

The sample code defines its own exception type with struct ValidationError <: Exception and raises it inside check_age() with throw(ValidationError(...)) when the age is below zero. Note e isa ValidationError, which tests the kind of exception.

A common early stumble is sticking to the standard error() function and losing the ability to tell errors apart. Being able to distinguish "invalid input" from "the network failed" is what lets you write a suitable response to each.

In professional work, the larger the program, the more this kind of error classification matters.

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

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