try, try! & try? what’s the difference, and when to use each in swift?

try, try! & try? 

Any function which can throw an error must be called using try, try? or try!:

  • "try" works within do/catch, or within another throwing function:
  • try is used with a do-catch statement and allows for a more detailed approach to error handling.

  • "try?" wraps the function's return value in an Optional (nil if an error was thrown). 
  • try? ignores our errors and will set them to nil if they happen to occur.

  • "try!" crashes the program at runtime if an error occurs.
  • try! force unwraps your code and guarantees that our function will never encounter an error. In the case that our function does throw an error our app will simply crash. 

How To Handle Errors with Do-Try-Catch :

In Swift, you handle errors with a do-try-catch block, to take appropriate action when an error is thrown.
Here’s an example.

Converting Errors to Optional Values with "try?":

You use try? to handle an error by converting it to an optional value. If an error is thrown while evaluating the try? expression, the value of the expression is nil. For example, in the following code.

Disable Error Handling with "try!" :

What happens when you try to access an implicitly unwrapped optional with a nil inside it? Yes, true, the app will CRASH! The same goes with try! it basically ignores the error chain, and declares a “do or die” situation. If the called function didn’t throw any errors, everything goes fine. But if it failed and threw an error, your application will simply crash.

let result = try! doSomething() // if an error was thrown, CRASH!

Create custom Error with localized description 

Here’s an example Create enum of custom errors.

How to throw an error in Swift :

Before we discuss handling errors, let’s first take a look at throwing them. That happens with the throw keyword in Swift. We have two options when you try calling a function that may throw

You can take responsibility of handling errors by surrounding your call within a do-catch block.

Thanks for reading!!

Post a Comment