Open In App

Difference between Try, Try?, and Try! in Swift

Last Updated : 16 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In every programming language, exception handling plays a crucial role in ensuring the reliability and stability of code. With the rise of Swift as a powerful and versatile programming language, developers are faced with new challenges and opportunities in managing errors and unexpected events. This article will provide a comprehensive overview of exception handling in Swift

Similar to any other programming language, Swift also has keywords that are used for handling underdefined behaviors of the program or we can say that handle exceptions. Swift provides 3 ways by which we can handle the undefined behavior of a program, they can be handled by using the keywords Try, Try? and Try!

Let us consider you have a function with a body as follows:

Swift




import Swift
  
func foo() throws -> Int? {
    print("I am inside foo()")
      throw SomeError //Part of code that will throw exception
}


Try

The first way to handle the exception is the basic way which has a similar syntax of error handling to any other language. This can be shown by the following code, It is similar to try and catch blocks in Java. We just wrap the error-throwing code inside a do block along with a keyword try keyword just in front of the function call causing the error. If any error is thrown it will be caught by the catch block just below it.

Swift




do {
    let x = try foo()
      print("This will be printed if there isn't any error.")
} catch {
    print("Cought Error while calling function foo()!")
}


Try?

Swift also has a second way of exception handling with the keyword Try along with ? with it. If we use try? in the code it will handle the error by just converting the error into an optional and continuing the flow. The use of try? can be seen in the following code:

Swift




let x = try? foo()
  
if let safex = x {
    print("x has a value which is \(safex)")
} else {
    print("x has a nil value")
}


Try? is mostly used with the guard keyword in swiftUI. Guard has similar working like if else but a bit different syntax. The following code shows the use of try? with the guard keyword. This type of code is used by programmers in cases where they are interested in finding and solving errors than just continuing the flow of the program.

Swift




guard let x = try? foo() else {
    print("Error in execution!")
}


Try!

Third way of handling errors in swiftUI is by using try!. In Swift, exclamation serves as an ignoring flag, where the user just avoids the error and continues the flow of the program without handling or changing anything for it. Whenever someone mentions try! before a code snippet which can cause error, it assumes that the user is more concerned about the flow of the program rather than the exception caused by the code. We can see the use of try! by following the code.

Try! is used in cases where the programmer is confident enough that the program will not throw any error.

Swift




let x = try! foo()
print("Execution will never reach here! Program halts above this line")


In most cases, the way of error handling depends upon the situation and the programmer’s Behavior mindset of handling the error. But from the above 3 ways try? is used mostly by the programmers.

Keyword

Result Type

Behaviour on Error

Try Any Error is propagated and must be caught using a do-catch statement.
Try? Optional Error is converted to nil and there is no need to use a do-catch statement.
Try! Non-Optional Error is force unwrapped, if there is an error thrown by a part of the program, the execution of the thread halts immediately.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads