0
0
iOS Swiftmobile~5 mins

Error handling (try, catch, throw) in iOS Swift

Choose your learning style9 modes available
Introduction

Error handling helps your app deal with problems without crashing. It lets you catch mistakes and fix or report them smoothly.

When reading a file that might not exist.
When downloading data from the internet that might fail.
When converting user input that might be wrong.
When calling a function that can fail and needs special handling.
Syntax
iOS Swift
do {
  try someFunctionThatThrows()
} catch {
  // handle error here
}

try means you call a function that can throw an error.

do-catch lets you catch and handle errors safely.

Examples
This example calls a function that might throw. If it throws, the catch block runs.
iOS Swift
func canThrow() throws {
  // might throw an error
}

do {
  try canThrow()
  print("Success")
} catch {
  print("Error caught")
}
Using try? converts errors to optional values, ignoring the error if it happens.
iOS Swift
func alwaysThrows() throws {
  throw NSError(domain: "Test", code: 1, userInfo: nil)
}

try? alwaysThrows()
Using try! means you are sure no error will happen. If it does, the app crashes.
iOS Swift
func alwaysThrows() throws {
  throw NSError(domain: "Test", code: 1, userInfo: nil)
}

try! alwaysThrows()
Sample App

This program checks if a number is negative. If it is, it throws an error. The do-catch block catches and prints the error.

iOS Swift
import Foundation

enum SimpleError: Error {
  case badInput
}

func checkNumber(_ number: Int) throws -> String {
  if number < 0 {
    throw SimpleError.badInput
  }
  return "Number is \(number)"
}

do {
  let result = try checkNumber(-5)
  print(result)
} catch {
  print("Caught an error: \(error)")
}
OutputSuccess
Important Notes

Always use do-catch to handle errors from throwing functions.

Use try? when you want to ignore errors and get nil instead.

Use try! only if you are sure no error will happen, or the app will crash.

Summary

Error handling keeps your app safe from crashes.

Use try to call functions that can throw errors.

Use do-catch to catch and handle errors gracefully.