xcode Swift 2.0 中的 do { } catch 不会处理从这里抛出的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32650050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:51:12  来源:igfitidea点击:

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

iosxcodeswift

提问by Varis Darasirikul

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

在我更新 swift 2.0 后,我在 do { try } catch 出现错误,如下图所示。

enter image description here

在此处输入图片说明

How can i fix this? Thanks!

我怎样才能解决这个问题?谢谢!

回答by Ronald Martin

The error is telling you that the enclosing catch is not exhaustive. This is because the auto-generated catchblock is only catching NSErrorobjects, and the compiler can't tell whether some other ErrorTypewill be thrown.

错误告诉您封闭的 catch 不是详尽无遗的。这是因为自动生成的catch块只捕获NSError对象,编译器无法判断是否ErrorType会抛出其他块。

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

如果您确定不会抛出其他错误,则可以添加另一个默认 catch 块:

do {
    objects = try managedObjectContext?.executeFetchRequest(request)
} catch let error1 as NSError {
    error = error1
    objects = nil
} catch {
    // Catch any other errors 
}

回答by Himanshu Mahajan

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.

除了处理您知道函数可能抛出的错误类型之外,您还需要使用通用 catch 块处理您不知道的错误类型。只需使用额外的 catch 块并向用户打印一些通用的错误消息。

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.

查看我的自定义错误处理代码。在这里,我创建了一个函数,如果它是奇数且小于 100,它将打印一个数字。我处理了两种类型的错误:Even 和 tooBig,为此我创建了一个 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.

最后一个 catch 块是处理未知错误。

Cheers!

干杯!