4

In Swift 3.0 , how to implement generic do-try-catch block to catch all errors that are thrown as a result of an operation. Apple documentation says to implement a enumerator of type ErrorType , which lists errors that are thrown. Suppose if we don't know what sort of errors that can be thrown by a operation then how to implement it. Below code is only for illustration purpose. Here i can catch the error but i don't know what causes this error. In objective C, we can get exact reason why error happened but here we only get the information that we have assigned to it.

enum AwfulError: ErrorType{
case CannotConvertStringToIntegertype
case general(String)}

func ConvertStringToInt( str : String) throws  -> Int
{
      if (Int(str) != nil) {
          return Int(str)!
      }
      else {
          throw  AwfulError.general("Oops something went wrong")
      }
}

let val = "123a"

do  {
    let intval: Int = try ConvertStringToInt(val)
    print("int value is : \(intval)")
}

catch let error as NSError {
    print("Caught error \(error.localizedDescription)")
}

I have found solution to my question.Code structure is listed below.

do {
    let str = try NSString(contentsOfFile: "Foo.bar",encoding: NSUTF8StringEncoding)
    print(str)
}
catch let error as NSError {
    print(error.localizedDescription)
}

Below code doesn't work because try expression is returning nil .To throw a error try expression should return a error and not a nil value. Type cast operation is an optional.

do {
    let intval  = try Int("123q")
    print( Int("\(intval)"))
}
catch let error as NSError {
    print(error.localizedDescription)
}
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
Jinil
  • 51
  • 6
  • You can catch for ErrorType *and* for other types. Example in the code of this answer: http://stackoverflow.com/a/31808605/2227743. (appzyourLife's answer also works). – Eric Aya Jul 11 '16 at 09:16
  • Thanks Eric. Your enum will work fine in your use-case as you know in advance that response of a request should have a nsdata and it should be converted to jSon. In my case i don't even know what are possible error that can be thrown from a operation.I want it to be generic one which captures all possible error. – Jinil Jul 11 '16 at 09:37
  • It's just an example to show you that you can catch defined errors, the ones conforming to ErrorType, *and* catch NSError ones, *the ones you don't know in advance*. :) And you can *also* add a generic catch like appzyourLife's one if you want. – Eric Aya Jul 11 '16 at 09:39

1 Answers1

0

You can just use catch to catch any kind of error.

do {
    try foo()
} catch {
    print(error)
}
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Thanks appzYourLife. How do you intent to throw an error from foo() ? Please note i would like get a generic response why the operation has failed. – Jinil Jul 11 '16 at 09:46
  • @Jinil: the function must be defined this way: `func foo() throws { ... }` – Luca Angeletti Jul 11 '16 at 09:59