Create And Throw Custom Error

-Ghost: Booo!!!
-Developer: ….
-Ghost: Null Pointer Exception!
-Developer: AAAA!!!

NullPointerException is one of the most known errors in programming. Most developers are afraid of that. Fortunately, in Swift Exceptions, don’t exist, we have Errors. Yet, we have our own NPE:

Nil error

Or when you go out of array range you will receive:

Index out of range

Those errors are in Swift already. Yet, can we create our custom error? Yes, we can.

A simple struct with a message which has to inheritance Error.

struct MyError: Error {
let message: String
init(_ message: String) {
self.message = message

And… that’s it. Now, we can use our error everywhere in the code. For instance, the function does some logic and may throw MyError :

func thorwMyError() throws {
    // some logic
throw MyError(“Something went wrong…”)

To use it we must wrap it to handle error:

do {
try thorwMyError()
catch {
“My custom error: \(error)”)

When functions throws then catch part of code is executed.


My custom error: MyError(message: “Something went wrong…”)