swift 报错 Call can throw, but it is not marked with 'try' and the error is not handled
Posted cui-cui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 报错 Call can throw, but it is not marked with 'try' and the error is not handled相关的知识,希望对你有一定的参考价值。
在开发中使用正则表达式时报了这样的问题:Call can throw, but it is not marked with ‘try‘ and the error is not handled,即:
let regex:NSRegularExpression = NSRegularExpression(pattern: "^1[3|4|5|7|8][0-9]{9}$", options: .caseInsensitive)
先看下在OC中的使用
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^1[3|4|5|7|8][0-9]{9}$" options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:self options:0 range:NSMakeRange(0, [self length])];
if (result) {
return YES;
}
return NO;
对比一下发现原因是没有添加错误处理,可以通过添加try解决。
最终解决后代码:
do{
let regex:NSRegularExpression = try NSRegularExpression(pattern: "^1[3|4|5|7|8][0-9]{9}$", options: .caseInsensitive)
let result:NSTextCheckingResult = regex.firstMatch(in: self, options:.reportProgress, range: NSMakeRange(0, self.count))!
if result != nil {
return true
}
}catch { }
return false
以上是关于swift 报错 Call can throw, but it is not marked with 'try' and the error is not handled的主要内容,如果未能解决你的问题,请参考以下文章
Can only call getServletHandlers on a running MetricsSystem解决方法
Lua - getOrientation() throw Attempt to call global (a nil value)
Swift 中的 throws 和 rethrows 有啥区别?
Node.js: http.js:691 throw new Error('Can\'t set headers after they are sent.')
Kendo UI 网格 - throw Error(kendo.format("Cannot call method '0' of 1 before it is initialized&qu