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

前端 未结 10 1853
走了就别回头了
走了就别回头了 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:49

    Swift 4:

    As per:

    https://developer.apple.com/documentation/foundation/nserror

    if you don't want to define a custom exception, you could use a standard NSError object as follows:

    import Foundation
    
    do {
      throw NSError(domain: "my error domain", code: 42, userInfo: ["ui1":12, "ui2":"val2"] ) 
    }
    catch let error as NSError {
      print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
      let uis = error.userInfo 
      print("\tUser info:")
      for (key,value) in uis {
        print("\t\tkey=\(key), value=\(value)")
      }
    }
    

    Prints:

    Caught NSError: The operation could not be completed, my error domain, 42
        User info:
            key=ui1, value=12
            key=ui2, value=val2
    

    This allows you to provide a custom string (the error domain), plus a numeric code and a dictionary with all the additional data you need, of any type.

    N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).

提交回复
热议问题