errir in swift

In Swift, errors can be handled using do-try-catch blocks. To throw an error, we need to define an error type that conforms to the Error protocol. We can then throw an instance of that error type using the "throw" keyword. Here's an example:

main.swift
enum CustomError: Error {
    case someError(String)
}

func divide(_ a: Int, by b: Int) throws -> Int {
    guard b != 0 else {
        throw CustomError.someError("Cannot divide by zero")
    }
    return a / b
}

do {
    let result = try divide(10, by: 0)
    print(result)
} catch CustomError.someError(let message) {
    print("Error: \(message)")
} catch {
    print("Unknown error occurred")
}
402 chars
20 lines

In the above example, we define a "CustomError" enum that conforms to the Error protocol. We then define a "divide" function that throws an instance of this error if the second argument (denominator) is zero. In the do-try-catch block, we call the "divide" function with 10 and 0 as arguments. Since the denominator is zero, the function throws an instance of CustomError with the message "Cannot divide by zero". This error is caught in the first catch block that matches the type of the thrown error. The second catch block is a generic catch-all block that catches any other type of error that might be thrown.

gistlibby LogSnag