try, try?, and try! 🎯Swift is a powerful and intuitive programming language developed by Apple for iOS, macOS, watchOS, and tvOS app development. In this tutorial, we'll dive into Swift's error handling mechanism using try, try?, and try!. Let's get started!
Error handling is essential to create robust and reliable apps. In Swift, we use the Throwable protocol to handle errors. Here, we'll discuss three Swift keywords that facilitate error handling: try, try?, and try!.
try 💡The try keyword is used when you expect the code to throw an error. When an error occurs, the execution halts, and the error can be handled using a do-catch statement.
do {
// Some code that throws an error
} catch {
// Error handling code
}do {
let contents = try String(contentsOfFile: "non-existent-file.txt")
print(contents)
} catch {
print("Error: File does not exist.")
}try? 💡try? is similar to try, but it returns an optional Result with two possible values: a wrapped value or nil. If an error occurs, it's wrapped in an Error object, and the resulting optional is nil.
if let result = try? {
// Some code that throws an error
} else {
// Handle the error
}try?) 📝if let contents = try? String(contentsOfFile: "non-existent-file.txt") {
print(contents)
} else {
print("Error: File does not exist.")
}try! 💡try! is a forceful version of try. Unlike try and try?, it does not provide a chance to handle errors. If an error occurs, the app will crash. Use it sparingly and only when you're absolutely sure that an error won't happen.
// Some code that throws an error
let result = try! {
// Some code that throws an error
}try!) 📝let contents = try! String(contentsOfFile: "non-existent-file.txt")
print(contents)What does `try!` do in Swift?
Now you have a good understanding of how to use try, try?, and try! for error handling in Swift. Remember to use try when you want to handle errors, try? when you want to return an optional, and try! with caution. Happy coding! 🚀