pawi
pawi

Reputation: 2523

Swift try-catch handling within a function or class

I try to become acquainted with the try&catch construct in Swift. Sorry, i couldn't find an answer in related posts!

Is it possible to hide this into a function or class as shown here?

class Test {

enum TestError:ErrorType{
    case a
    case b
 }

func a(s:String) throws -> String{
    if s == "OK" {
        return "OK"
    }else{
        throw TestError.a
    }
}

func b(s:String) throws -> String{
    if s == "OK" {
        return "OK"
    }else{
        throw TestError.b
    }
}

func doTest(str:String) -> String{
    do{
        let s = try a(b(str)) // <= ERROR
    }catch TestError.a{
        return "a failed!"
    }catch TestError.b{
        return "b failed!"
    }
}

} I always get

error: errors thrown from here are not handled because the enclosing catch is not exhaustive

Is it in principle impossible and only applicable in the main program? Or is there a way around?

Upvotes: 1

Views: 776

Answers (1)

Eric Aya
Eric Aya

Reputation: 70098

The compiler needs a clause in case a different error is thrown. I like to do a global catch like this, by casting to NSError:

do {
    return try a(b(str))
} catch TestError.a {
    return "a failed!"
} catch TestError.b {
    return "b failed!"
} catch let error as NSError {
    return "\(error.description)"
}

You also have to return the String at the try.

Upvotes: 3

Related Questions