Errors thrown from here are not handled for do { } catch in Swift 2.0

后端 未结 2 633
渐次进展
渐次进展 2021-02-03 21:34

After i update swift 2.0 i got an error with do { try } catch like an image below.

How can i fix this? Thanks!

相关标签:
2条回答
  • 2021-02-03 21:55

    The error is telling you that the enclosing catch is not exhaustive. This is because the auto-generated catch block is only catching NSError objects, and the compiler can't tell whether some other ErrorType will be thrown.

    If you're sure no other errors will be thrown, you can add another default catch block:

    do {
        objects = try managedObjectContext?.executeFetchRequest(request)
    } catch let error1 as NSError {
        error = error1
        objects = nil
    } catch {
        // Catch any other errors 
    }
    
    0 讨论(0)
  • 2021-02-03 21:58

    In addition to handling the error types you know that your function can throw, you need to handle the error type you don't know with universal catch blocks. Just use extra catch block and print some generalized error message to user.

    See my custom error handling code. Here, I have created a function that will print a number if it is odd and less than 100. I have handled with two types of Errors : Even and tooBig, for this I have created an enum of type ErrorType.

       enum InvalidNumberError : ErrorType{
            case even
            case tooBig
       }
    
      //MARK: this function will print a number if it is less than 100 and odd
    
       func printSmallNumber(x :Int) throws{
    
            if x % 2 == 0 {
                 throw InvalidNumberError.even
            }
            else if x > 100 {
                 throw InvalidNumberError.tooBig
            }
    
            print("number is \(x)")
       }
    

    Error handling code is:

        do{
            try printSmallNumber(67)
        }catch InvalidNumberError.even{
            print("Number is Even")
        }catch InvalidNumberError.tooBig{
            print("Number is greater tha 100")
        }catch{
            print("some error")
        }
    

    Last catch block is to handle the unknown error.

    Cheers!

    0 讨论(0)
提交回复
热议问题