Swift
error handling
exceptions
custom error messages
programming tips

Simplest way to throw an error/exception with a custom message in Swift?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Swift, Apple's modern programming language, provides a robust mechanism for handling errors and exceptions. When developing iOS, macOS, watchOS, or tvOS apps, it's essential to ensure that our applications handle unexpected situations gracefully. While Swift provides several mechanisms to handle errors, sometimes, you may need to throw an error with a custom message to provide more context. This article explains the simplest way to throw an error with a custom message in Swift, along with underlying technical explanations and examples.

Error Protocol in Swift

In Swift, errors are represented by values of types that conform to the Error protocol. This is a simple protocol with no requirements. You can define a custom error type by creating an enumeration that conforms to the Error protocol. This mechanism is robust and allows you to maintain a list of potential errors your application might encounter.

Example of a Custom Error Type

swift
1enum CustomError: Error {
2    case invalidInput(message: String)
3    case networkError(message: String)
4    case unknown(message: String)
5}

In the example above, CustomError is an enumeration conforming to the Error protocol with associated values. Each case has a string message that provides additional information.

Throwing an Error

To throw an error in Swift, you use the throw keyword. Here’s a simple example of how to throw an error with a custom message:

swift
1func validateInput(input: String) throws {
2    guard input == "valid" else {
3        throw CustomError.invalidInput(message: "The input provided is invalid.")
4    }
5}

In the validateInput function, we check if the input is "valid". If it's not, we throw a CustomError with an associated custom message.

Handling a Thrown Error

Errors in Swift are typically handled using a do-catch block. Within this block, you can catch specific errors and take appropriate action.

swift
1do {
2    try validateInput(input: "invalid")
3} catch CustomError.invalidInput(let message) {
4    print("Caught an error: \(message)")
5} catch {
6    print("An unexpected error occurred: \(error)")
7}

In the do-catch block, we attempt to call validateInput with an incorrect input. When it throws an error, we catch it and print the custom message.

Key Points for Custom Error Handling

Key PointDescription
Error DefinitionDefine a custom error using an enum that conforms to the Error protocol.
Throwing ErrorsUse the throw keyword to signal an error condition.
Error CatchingUse do-catch blocks to handle errors and differentiate actions based on error type.
Custom MessagesPass custom messages using associated values to provide more detailed error information.

Additional Error Handling Features in Swift

Swift offers additional features for error handling, which can make your code cleaner and more descriptive:

Propagating Errors

You can propagate errors in Swift by marking a function with throws. This allows the calling function to handle the error instead.

swift
func anotherFunction() throws {
    try validateInput(input: "anotherInvalidInput")
}

Using try? and try!

  • try? converts errors to optional results, returning nil on failure.
  • try! assumes no errors occur and causes a runtime crash if an error is thrown.
swift
let result = try? validateInput(input: "optionalInput")

This method will set result to nil if validateInput throws an error.

Error and Exception Best Practices

  1. Default Branches: Always add a default catch block to handle unexpected errors.
  2. Proper Error Messages: Use descriptive messages for better debugging and understanding.
  3. Documentation: Document possible errors for each function.

By adhering to these principles, your code becomes more resilient, easier to maintain, and provides a better user experience by highlighting potential issues as early as possible. Understanding Swift’s error handling mechanisms, especially with custom messages, is crucial for robust application development.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms