Swift Exhaustive Error Handling

Hello, I have a situation where Xcode 7 beta is complaining that "Errors thrown from here are not handled because the enclosing catch is not exhaustive." But I'm confused because, to me, it does appear that my cases are exhaustive, covering all of the one cases in my ErrorType enum.


Here's my code:


import UIKit

protocol SearchItemView {
    var center: CGPoint { get }
    var radius: CGFloat { get }
    var color: UIColor { get }   
    init(center: CGPoint, radius: CGFloat, color: UIColor)
}

enum SearchViewModelError: ErrorType {
    case InvalidClassName  // only one error case
}
class SearchViewModel {
    private var searchItemViewClassName: String
    private var searchItems: [SearchItemView] = []
    init(searchItemViewClassName: String) {
        self.searchItemViewClassName = searchItemViewClassName
        do {
            try createSearchItemView() // Xcode error here about lacking exhaustive cases; can't build and run
        } catch SearchViewModelError.InvalidClassName {  // covers the one error case
        }
    }
    func createSearchItemView() throws -> SearchItemView {
        guard let searchItemView: SearchItemView = NSClassFromString(searchItemViewClassName) as? SearchItemView else {
            throw SearchViewModelError.InvalidClassName  // only one possible error thrown
        }
        return searchItemView
    }
}


I can eliminate the error by adding an extra superfluous catch to catch anything else: "catch {}", after the first catch I have.

Accepted Answer

a. The compiler can't reason about what errors might be thrown by 'createSearchItemView' because (in the absence of further information) it can't assume that the method isn't overridden by something that throws other errors.


b. Even if it could reason that way (e.g. if you mark 'createSearchItemView' final), I doubt that the optimization to reason that way exists in the current compiler version.


c. Reasoning about control flow — and now I mean you reasoning about what 'catch' clauses you need — is one of the defects of exception mechanisms. Swift error handling is said to be designed not to be an exception mechanism, and not to impose the need to reason about control flow. Adding 'catch {}' makes it clear to the reader of the code what's going to happen, without having to look elsewhere in the code.


d. You don't actually need a 'catch SearchViewModelError.InvalidClassName' clause in this case. Since SearchViewModelError conforms to ErrorType, a simple 'catch' will catch it

Swift Exhaustive Error Handling
 
 
Q