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
}

The Do-Catch syntax allows to catch a thrown error, and automatically creates a constant named error available 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)
}

It’s also possible to chain different catch statements. This is convenient if several types of errors can be thrown in the Do block.

Here the Do-Catch will first attempt to cast the error as a CustomError, then as an NSError if the custom type was not matched.

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