Swift 3 Programming Language – Error handling

Error Handling

You can define custom errors by defining an enum which extens Error protocol


// Example of custom `enum` for types of errors for Printer
enum PrinterError: Error {
    case outOfPaper
    case noToner
    case onFire

How to throw an Error?

  • Use throw to throw an error
  • throws to mark a function that can throw an error
  • when a function throws an error, it returns immediately


// Example of a function throwing an `error` of type `PrinterError`
func send(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never has toner" {
        throw PrinterError.noToner
    } else if printerName == "Out of paper" {
        throw PrinterError.outOfPaper
    } else if printerName == "On fire" {
        throw PrinterError.onFire
    } else {
        return "Job Sent to printer - \(printerName)"

Example of handling error with do-catch

// Using do-catch to handle errors.

// Example to handle errors with do-catch
do {
    print(try send(job: 007, toPrinter: "Sagar Kothari's personal printer"))
} catch {

few more examples

// Example of a statement thworing an error
do {
    print(try send(job: 007, toPrinter: "On fire"))
} catch {
    print("Error is - \(error)")
// Another example of thworing an error
    print(try send(job: 007, toPrinter: "Never has toner"))
} catch {
    print("Error is - \(error)")

Example of handling error with multiple catch

// Multiple catch blocks to handle specific Error.
do {
    let printerResponse = try send(job: 123, toPrinter: "Sagar's Cabin")
    throw PrinterError.noToner
} catch PrinterError.outOfPaper {
    print("Oh God. Someone please get me papers for printer.")
} catch let printerError as PrinterError {
    print("Some printer error - \(printerError)")
} catch {
    print("Some strange error occured - \(error)")

try? method to handle errors

Another way to handle errors is to use try? to convert result into an optional. If function throws error, error is discarded & result is nil. Otherwise result is an optional containing value

print("Successful printer try is - \(try? send(job: 5, toPrinter: "Amit's printer"))")
print("Failure printer try is - \(try? send(job: 5, toPrinter: "On fire"))")

Output of above code

Job Sent to printer - Sagar Kothari's personal printer
Error is - onFire
Error is - noToner
Job Sent to printer - Sagar's Cabin
Some printer error - noToner
Successful printer try is - Optional("Job Sent to printer - Amit\'s printer")
Failure printer try is - nil

Click here to open actual swift-playground file for above illustration