DevPrep

All topics › Object-oriented programming (OOP)

Error handling and exceptions in OOP

Junior

Essence

In classic OOP languages (Java, C#, C++) errors are exceptions: an object is thrown, the stack unwinds to the nearest catch, and any call may implicitly abort execution. Swift takes a different route: an error is a value, not an exception.

How it works in Swift

import Foundation

enum PaymentError: Error {
    case insufficientFunds(missing: Decimal)
    case cardExpired
}

// Typed throws (Swift 6): the error type is part of the signature.
func charge(_ amount: Decimal, balance: Decimal) throws(PaymentError) {
    guard balance >= amount else {
        throw .insufficientFunds(missing: amount - balance)
    }
}

do {
    try charge(100, balance: 30)
} catch .insufficientFunds(let missing) {
    print("need \(missing) more")          // need 70 more
} catch {
    print("other: \(error)")
}

// Error as a value: Result keeps success/failure for later.
let result = Result { try charge(10, balance: 50) }
if case .failure(let e) = result { print(e) }

let maybe: Void? = try? charge(1, balance: 0)  // nil on failure
print(maybe == nil)                             // true

What the interviewer looks for

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store