Ad space (banner)
๐ŸฆSwift Lessons
Lesson 25 / 68

Writing a Custom Error Type

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

An enum conforming to the Error protocol gives you an error of your own. Giving each kind of failure its own case makes it much easier to tell what went wrong when you catch it.

The sample code has the ValidationError enum carry an invalidAge(String) case and throws it from checkAge() when the age is negative. Notice how catch ValidationError.invalidAge(let message) even extracts the message the error carries.

A common stumbling block for beginners is sticking with the bare Error protocol 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, being able to split handling by error kind through pattern matching is what makes Swift error handling so powerful.

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

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