1

Catch clauses in Swift must be exhaustive. Does it mean I always need to use a wildcard or empty catch clauses whenever I want to avoid error propagation? Example:

enum Oops: Error {
    case oh, ouch, meh
}

func troublemaker() {
    do { throw Oops.meh }
    catch Oops.oh {}
    catch Oops.ouch {}
    catch Oops.meh {}
    // Error: Error is not handled because the enclosing catch is not exhaustive
}

Of course, it is fixed if I add throws to the function. Same goes for adding either catch {} or catch _ {}.

But is there any way to make exhaustive catch blocks other way? Like, perhaps defining the allowed type of the error to throw, so my enum Error would make it exhaustive?

Robo Robok
  • 21,132
  • 17
  • 68
  • 126
  • 1
    You cannot specify which errors are thrown. Compare https://stackoverflow.com/questions/39618095/can-i-restrict-the-type-that-a-function-throws-in-swift or https://stackoverflow.com/questions/30740997/what-is-the-difference-between-swift-2-0-do-try-catch-and-regular-java-c-c-ex. – Martin R Jul 14 '17 at 14:07
  • 1
    See also https://stackoverflow.com/q/40718542/2976878 – Hamish Jul 14 '17 at 14:08

1 Answers1

1

If you simply don't like the multiple catch blocks, catch all errors at once and then switch error types

func troublemaker() {
    do { throw Oops.meh }
    catch let error{
        switch error {
        case Oops.meh:
            print("It works!")
            break
        default:
            print("Oops something else is wrong")
            break
        }
    }
}
Fangming
  • 24,551
  • 6
  • 100
  • 90