DEV Community

Ajithmadhan
Ajithmadhan

Posted on

Swift - Error handling

An error (exception) is an unexpected event that occurs during program execution. For example,

var numerator = 10
var denominator = 0

// try to divide a number by 0
var result = numerator / denominator // error code
Enter fullscreen mode Exit fullscreen mode

Steps For Error Handling in Swift

  1. Create an enum that represents the types of errors.
  2. Create a throwing function using the throws keyword.
  3. Call the function using the try keyword.
  4. Wrap the code with try in the do {...} block and add the catch {...} block to handle all errors.

Example,

// create an enum with error values
enum DivisionError: Error {

  case dividedByZero
}

// create a throwing function using throws keyword
func division(numerator: Int, denominator: Int) throws {

  // throw error if divide by 0
  if denominator == 0 {
    throw DivisionError.dividedByZero
  }

  else {
    let result = numerator / denominator
    print(result)
  }
}

// call throwing function from do block
do {
  try division(numerator: 10, denominator: 0)
  print("Valid Division")
}

// catch error if function throws an error
catch DivisionError.dividedByZero {
  print("Error: Denominator cannot be 0")
}
Enter fullscreen mode Exit fullscreen mode

Disable Error Handling

In Swift, sometimes we can be confident that the throwing function won't throw an error at runtime.

In that case, we can write try! during the function call to disable the error handling. For example,

enum DivisionError: Error {

  case dividedByZero
}

func division(numerator: Int, denominator: Int) throws {
  if denominator == 0 {
    throw DivisionError.dividedByZero
  }

  else {
    let result = numerator / denominator
    print("Result:", result)
  }
}

// disable error handling
try! division(numerator: 10, denominator: 5)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)