original articles, welcome reprint. Reprint Please specify: Dongsheng's blog
can be put in Try subsequent calls to functions or methods are required, and they are likely to throw an error after the arguments declared by these functions or methods are appended with the throws keyword that indicates that the function or method can throw an error.
The example code for declaring a throw error method is as follows:
Delete Note Record method func remove (Model:note) throws { ...} Query all record Data methods Func FindAll () throws, [Note] { ...}
The above codeRemove (_:)method does not return a value,throwsThe keyword is placed after the parameter. findAll ()has a return valuethrowsThe keyword is placed between the parameter and the return value type.
Throw an error in a function or method
A function or method can declare a throw error because an error is generated and thrown in a function or method, so that a function or method declaration throws an error in practical sense.
In generating and throwing the wrong way:
to pass through a function or method. Throw statement that artificially throws an error.
Other calls in the function or method can throw an error function or method, but no capture processing can cause errors to be propagated.
The sample code is as follows:
Remove the Note method func remove (Model:note) throws { Guard Let date = Model.date else { //judgment thrown when there is a guard statement //throw "PRIMARY key is empty" Error throw Daoerror.primarykeynull } //Compare date primary key is equal for (index, note) in Listdata.enumerate () where Note.date = = Date { listdata.removeatindex (index) }}//Query all data methods Func FindAll () throws, [Note] { Guard Listdata.count > 0 Else { //judgment thrown when there is a guard statement //throws "No data" error. throw Daoerror.nodata } Return ListData} func printnotes () throws { //declaration throws error Let datas = Try FindAll () for Note in datas {
print ("Date: \ (note.date!) -Content: \ (note.content!) }} Try PrintNotes ()
Guard The statement is best at dealing with this early judgment, provided false the case throws an error.
findAll () The statement itself may produce an error, but it does not use the Catch The statement is captured and processed, which causes the error to propagate to the caller of the function or method, and if the caller does not capture the processing, the last program will have a run-time error.
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
?
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
Learning Swift from scratch (Day54)-throwing errors