Simplest way to throw an error/exception with a custom message in Swift 2?

前端 未结 10 1873
走了就别回头了
走了就别回头了 2020-12-22 15:57

I want to do something in Swift 2 that I\'m used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):



        
10条回答
  •  滥情空心
    2020-12-22 16:46

    Based on @Nick keets answer, here is a more complete example:

    extension String: Error {} // Enables you to throw a string
    
    extension String: LocalizedError { // Adds error.localizedDescription to Error instances
        public var errorDescription: String? { return self }
    }
    
    func test(color: NSColor) throws{
        if color == .red {
            throw "I don't like red"
        }else if color == .green {
            throw "I'm not into green"
        }else {
            throw "I like all other colors"
        }
    }
    
    do {
        try test(color: .green)
    } catch let error where error.localizedDescription == "I don't like red"{
        Swift.print ("Error: \(error)") // "I don't like red"
    }catch let error {
        Swift.print ("Other cases: Error: \(error.localizedDescription)") // I like all other colors
    }
    

    Originally published on my swift blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/

提交回复
热议问题