Skip to content
DeveloperMemos

The Difference Between try, try! and try? in Swift

Swift, Error Handling2 min read

Error handling is an essential part of writing robust and reliable code in Swift. The language provides multiple ways to handle errors, and try, try!, and try? are commonly used constructs for dealing with functions that can potentially throw errors. In this article, we will dive into the differences between these three constructs and examine their use cases through examples.

The try Keyword

The try keyword is used to call a function that can potentially throw an error. When using try, you're indicating to the compiler that you acknowledge the possibility of an error and are handling it appropriately. You need to enclose the try expression within a do-catch block to handle any thrown errors.

Here's an example that demonstrates the usage of try:

1func divide(_ numerator: Int, by denominator: Int) throws -> Int {
2 guard denominator != 0 else {
3 throw DivisionError.divideByZero
4 }
5 return numerator / denominator
6}
7
8do {
9 let result = try divide(10, by: 2)
10 print("Result: \(result)")
11} catch {
12 print("Error: \(error)")
13}

In the above code, we define a divide function that can throw a DivisionError if the denominator is zero. Inside the do block, we call the function using try. If an error is thrown, it is caught by the catch block, where we can handle it accordingly.

The try! Keyword

The try! keyword is used when you are confident that a function will not throw an error at runtime. It forcefully tries to execute the function and expects it to succeed. If an error is indeed thrown, it will cause a runtime error, terminating your program.

Here's an example that demonstrates the usage of try!:

1let result = try! divide(10, by: 2)
2print("Result: \(result)")

In the above code, we use try! to call the divide function. Since we are certain that the division will not result in an error, we can safely use try! without the need for error handling. However, if an error does occur, a runtime error will be triggered.

It's important to note that using try! should be done judiciously. If the function does throw an error unexpectedly, it can lead to crashes and unexpected behavior in your application.

The try? Keyword

The try? keyword is used when you want to handle an error gracefully by converting it into an optional value. Instead of throwing an error, the function returns nil if an error occurs, allowing you to handle the failure case more conveniently.

Here's an example that demonstrates the usage of try?:

1let result = try? divide(10, by: 0)
2if let value = result {
3 print("Result: \(value)")
4} else {
5 print("Error occurred")
6}

In the above code, we use try? to call the divide function with a denominator of 0. Since dividing by

0 would result in an error, the result will be nil. We can then check the result using an optional binding. If the result is non-nil, we print the value; otherwise, we handle the error case.

Using try? can be useful in situations where the error is not critical and you want to gracefully handle failures without causing an abrupt termination of the program.

Conclusion

In summary, try is used when you want to handle errors explicitly using a do-catch block, try! is used when you are confident that a function won't throw an error, and try? is used when you want to handle errors gracefully by converting them into optional values.

Understanding the differences between try, try!, and try? is crucial for effective error handling in Swift. By using the appropriate construct based on your requirements, you can ensure your code handles errors gracefully and provides a robust user experience.