Skip to content

Latest commit

 

History

History
106 lines (77 loc) · 3.51 KB

error_handling_in_swift.md

File metadata and controls

106 lines (77 loc) · 3.51 KB

Error Handling in Swift

Error handling is a fundamental practice in programming that allows you to deal with unexpected situations or conditions in your code.

Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

Why Error Handling?

  1. Robustness: Makes your app more resilient by gracefully handling failures.
  2. User Experience: Allows you to provide meaningful error messages to the user.
  3. Debugging: Easier to debug issues when errors are properly categorised and handled.

Basic Concepts

  • Throwing Errors: Your functions can throw errors to indicate that they failed to perform an action.
  • Catching Errors: A do-catch statement allows you to catch and handle errors gracefully.
  • Propagating Errors: You can propagate errors from a function to the code that calls that function.

Define an Error Type

First, define an error type that conforms to the Error protocol. This will represent the errors that your function can throw.

enum JokeError: Error {
    case invalidURL
    case noData
    case parsingError
}

Throwing Errors

Mark your function with the throws keyword to indicate that it can throw an error.

func fetchJoke() throws -> String {
    // Your code here
    throw JokeError.invalidURL // Example of throwing an error
}

Catching Errors

Use a do-catch statement to catch errors.

do {
    let joke = try fetchJoke()
    print("Joke: \(joke)")
} catch JokeError.invalidURL {
    print("Invalid URL.")
} catch JokeError.noData {
    print("No data received.")
} catch JokeError.parsingError {
    print("Failed to parse data.")
} catch {
    print("An unknown error occurred: \(error)")
}

Propagating Errors

If you don't want to handle the error in the current function but want to let it propagate to the calling function, use throws in your function signature.

func fetchJokeAndPrint() throws {
    let joke = try fetchJoke()
    print("Joke: \(joke)")
}

Summary

Error handling in Swift is a powerful feature that helps you write robust code.

By understanding how to throw, catch, and propagate errors, you can build apps that can gracefully handle unexpected situations, making your apps more reliable and user-friendly.

Resources


How was this resource?
😫 😕 😐 🙂 😀
Click an emoji to tell us.