original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
when using Try when you do error handling, you often see Try followed by a question mark ( ? ) or an exclamation point ( ! ), what difference do they have?
1. use try?
try? Will convert the error to an optional value when calling the try? + function or method statement, if a function or method throws an error, the program does not crash and returns a Nil , and an optional value is returned if no error is thrown.
The sample code is as follows:
Query all data methods Func findAll () throws-> [Note] {guard Listdata.count > 0 Else {//throws "No data" error. Throw Daoerror.nodata} return listData} Let Datas = try? FindAll () print (datas)
in the code aboveLet datas = try? FindAll ()statement that uses thetry?,datasis an optional value, in this case the outputNil. Used atry?statement is not necessary to useDo-catchstatement to wrap it up.
2. use try!
Use try! can break the chain of error propagation. The error is thrown and propagated to its callers, which forms a chain of propagation, but sometimes does not want to let the error spread, you can use try! statement.
Modify the above code as follows:
//querying all Data Methods Func findall () throws-> [Note] { guard listData.count > 0 else { //throws "no data" error. throw DAOError.NoData } return listdata} func printnotes () { let datas = try! findall () ① for note in datas { print ("Date : \ (note.date!) -content: \ (note.content!) ") }}printnotes ()
②
Code printnotes () The function does not declare a throw error and does not need to be called when calling it Try keywords, error propagation chain in printnotes () inside the function was broken.
Code willtry Dao.findall ()statement insteadtry! findAll (), inTryadded an exclamation mark (!) so that the compiler does not requireprintnotes ()method declaration throws an error,try!The error propagation chain is broken, but if there is a real error, a run-time error causes the program to crash.
so use try! when breaking the chain of error propagation, you should ensure that the program does not have errors.
Welcome to follow Dongsheng Sina Weibo@tony_Dongsheng.
Learn about the latest technical articles, books, tutorials and information on the public platform of the smart Jie classroom
650) this.width=650; "title=" 00.png "alt=" Wkiom1bc9d3hj5yfaaas2mbeznc204.png "src=" http://s3.51cto.com/wyfs02/M02/ 7c/f1/wkiom1bc9d3hj5yfaaas2mbeznc204.png "/>
More ProductsIOS,Cocos, mobile Design course please pay attention to the official website of Chi Jie Classroom:http://www.zhijieketang.com
Smart-Jie Classroom Forum Website:http://51work6.com/forum.php
This article is from the "Dongsheng-ios Technical Consultant" blog, make sure to keep this source http://tonyguan.blog.51cto.com/701759/1748320
Learn notes from scratch (day 55)-Using the try and try! differences