How to handle errors using 'try-catch' in swift?

Example:


  enum SimpleError: Error {
      case invalid
  }
  func checkValue(value: Int) throws -> String {
      if value <= 0 {
          throw SimpleError.invalid
      }
      return "Valid"
  }
  

This function throws an error for non-positive numbers.

Solution:


  do {
      let result = try checkValue(value: -5)
      print(result)
  } catch SimpleError.invalid {
      print("Value is invalid")
  }
  

Here we use 'try-catch' to handle the error thrown by the function.

Beginner's Guide to Swift