Catching different error types

suggest change

Let’s create our own error type for this example.

enum CustomError: ErrorType {
    case SomeError
    case AnotherError
}

func throwing() throws {
    throw CustomError.SomeError
}
enum CustomError: Error {
    case someError
    case anotherError
}

func throwing() throws {
    throw CustomError.someError
}

do-catch catches a thrown error and automatically creates a constant named error in the catch block:

do {
    try throwing()
} catch {
    print(error)
}

You can also declare a variable yourself:

do {
    try throwing()
} catch let oops {
    print(oops)
}

You can chain catch clauses. That is useful when the do block can throw more than one error type.

The first sample tries to match CustomError, then NSError if that cast fails. The first enum above is Swift 2 (ErrorType); the second is Swift 3 (Error).

do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch let error as NSError {
    print(error)
}

In Swift 3, no need to explicitly downcast to NSError.

do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch {
    print(error)
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents