Bleep
Bleep

Reputation: 431

Error Handling in Swift 3

I'm migrating my code over to Swift 3 and see a bunch of the same warnings with my do/try/catch blocks. I want to check if an assignment doesn't return nil and then print something out to the console if it doesn't work. The catch block says it "is unreachable because no errors are thrown in 'do' block". I would want to catch all errors with one catch block.

let xmlString: String?
    do{
        //Warning for line below: "no calls to throwing function occurs within 'try' expression
        try xmlString = String(contentsOfURL: accessURL, encoding: String.Encoding.utf8)

        var xmlDict = XMLDictionaryParser.sharedInstance().dictionary(with: xmlString)
        if let models = xmlDict?["Cygnet"] {
            self.cygnets = models as! NSArray
        }

    //Warning for line below: "catch block is unreachable because no errors are thrown in 'do' block
    } catch {
        print("error getting xml string")
    }

How would I write a proper try catch block that would handle assignment errors?

Upvotes: 40

Views: 45756

Answers (1)

OOPer
OOPer

Reputation: 47886

One way you can do is throwing your own errors on finding nil.

With having this sort of your own error:

enum MyError: Error {
    case FoundNil(String)
}

You can write something like this:

    do{
        let xmlString = try String(contentsOf: accessURL, encoding: String.Encoding.utf8)
        guard let xmlDict = XMLDictionaryParser.sharedInstance().dictionary(with: xmlString) else {
            throw MyError.FoundNil("xmlDict")
        }
        guard let models = xmlDict["Cygnet"] as? NSArray else {
            throw MyError.FoundNil("models")
        }
        self.cygnets = models
    } catch {
        print("error getting xml string: \(error)")
    }

Upvotes: 67

Related Questions