Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 313
Bleep Avatar asked Aug 08 '16 17:08

Bleep


People also ask

How does Swift handle fatal errors?

According to Swift Error Handling Rationale, the general advice is: Logical error indicates that a programmer has made a mistake. It should be handled by fixing the code, not by recovering from it. Swift offers several APIs for this: assert() , precondition() and fatalError() .

Why error handling required explain types of error?

Error handling refers to the response and recovery procedures from error conditions present in a software application. In other words, it is the process comprised of anticipation, detection and resolution of application errors, programming errors or communication errors.

How do you handle errors in catch block?

You can put a try catch inside the catch block, or you can simply throw the exception again. Its better to have finally block with your try catch so that even if an exception occurs in the catch block, finally block code gets executed.


1 Answers

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)")
    }
like image 70
OOPer Avatar answered Nov 08 '22 06:11

OOPer