xcode 错误“调用可以抛出,但未标记为‘try’且未处理错误”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32997955/
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
Error "Call can throw, but is not marked with 'try' and the error is not handled"
提问by Robert S
Getting an error with this piece of code "Call can throw, but is not marked with 'try' and the error is not handled"
这段代码出现错误“调用可以抛出,但未标记为‘尝试’且未处理错误”
I am using the Xcode 7.1 the latest beta and swift 2.0
我使用的是最新的测试版 Xcode 7.1 和 swift 2.0
func checkUserCredentials() -> Bool {
PFUser.logInWithUsername(userName!, password: password!)
if (PFUser.currentUser() != nil) {
return true
}
return false
回答by Charles A.
Swift 2.0 introduces error handling. The error indicates that logInWithUsername:password:
can potentially throw an error, and you must do something with that error. You have one of a few options:
Swift 2.0 引入了错误处理。该错误表示logInWithUsername:password:
可能会引发错误,您必须对该错误执行某些操作。您有以下几种选择之一:
Mark your checkUserCredentials()
functional as throws
and propagate the error to the caller:
将您的checkUserCredentials()
功能标记为throws
并将错误传播给调用者:
func checkUserCredentials() throws -> Bool {
try PFUser.logInWithUsername(userName!, password: password!)
if (PFUser.currentUser() != nil) {
return true
}
return false
}
Use do
/catch
syntax to catch the potential error:
使用do
/catch
语法来捕捉潜在的错误:
func checkUserCredentials() -> Bool {
do {
try PFUser.logInWithUsername(userName!, password: password!)
}
catch _ {
// Error handling
}
if (PFUser.currentUser() != nil) {
return true
}
return false
}
Use the try!
keyword to have the program trap if an error is thrown, this is only appropriate if you know for a fact the function will never throw given the current circumstances - similar to using !
to force unwrap an optional (seems unlikely given the method name):
try!
如果抛出错误,则使用关键字让程序陷入陷阱,这仅适用于您知道在当前情况下该函数永远不会抛出的事实 - 类似于使用!
强制解包可选(鉴于方法名称似乎不太可能) :
func checkUserCredentials() -> Bool {
try! PFUser.logInWithUsername(userName!, password: password!)
if (PFUser.currentUser() != nil) {
return true
}
return false
}