[问题]
折腾:
期间,用代码:
do { let opt = try 。。。 opt.start { response in if let err = response.error { 。。。 } 。。。 let respJsonDict = NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) print("respJsonDict=\(respJsonDict)") } } catch let error { NSLog("got an error creating the request: \(error)") }
结果出错:
Call can throw, but it is not marked with ‘try’ and the error is not handled
如图:
[解决过程]
1.很明显,此处对于
NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers)
需要外部加上try。
但是特殊一点的是,此处外部还有个:
do
try
catch
所以此处要搞清楚,如何加对应的try
2.搜:
swift Call can throw, but it is not marked with ‘try’ and the error is not handled
参考:
去试试,结果又遇到了:
3.后来参考:
可以指定对应类型为dictionary:
let respJsonDict:NSDictionary = NSJSONSerialization.JSONObjectWithData(response.data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
[总结]
如果某个函数,某行代码,提示会throw抛出一场,则直接在对应代码处,外部加上try catch的代码就好了:
do { xxx = try yyyy // yyyy could be throw error } catch{ //process error }
然后对于嵌套try…catch的话,则没有任何问题,直接嵌套即可:
do { xxx = try yyyy // yyyy could be throw error do { zzz = try aaaaa // aaaa could be throw error } catch{ //process error } } catch{ //process error }
即可。
转载请注明:在路上 » [已解决]Swift代码出错: Call can throw, but it is not marked with try and the error is not handled