The error handling mode of the Swift 1.x has many drawbacks, for example: in order to save time in programming, passing a nil to the error parameter, or not judging whether the error is nil after the method call is complete, and not handling error.
- Let contents = nsstring (contentsoffile:filepath,
- Êencoding:nsutf8stringencoding, Error:nil)//error parameter pass a nil
Or
- var err:nserror?
- Let contents = nsstring (contentsoffile:filepath,
- êencoding:nsutf8stringencoding, Error: &err)
Bad programming habits, because objective-c and Swift 1.x do not have a mandatory processing mechanism, so once a real error occurs, the program will crash.
The same example of reading a string from a file, if using the Swift2 error handling mode code is as follows:
- Import Foundation
- Do {//to do some action
- Let str = try NSString (Contentsoffile:filepath,
- êencoding:nsutf8stringencoding)//What to try to do
- } catch let err as nserror {//Enter catch code block if failed
- Err.Description
- }
Do-try-catch This error pattern is very similar to the exception handling mechanism in Java, which is intended to be an attempt todo one thing and catch (catch) processing if it fails.
Catch error
The syntax for the complete Do-try-catch error handling pattern is as follows:
- do {
- Try Statement
- Successfully working with statement groups
- } catch match Error {
- Error Handling Statement Group
- }
An error can be generated in a try statement, and of course it may not produce an error, and if an error occurs, thecatch handles the error. a catch code block can have multiple, and the error is determined by which catch code block is handled by the error after the catch. The number of error types determines How many catch can be. Let's introduce the error type first.
Type of error
In Swift, the error type must conform to the ErrorType protocol, followed by the match of the error type, which should be designed as an enumeration type, which is ideal for associating a set of related values.
If we write access to the database table program and implement operations such as inserting, deleting, modifying, and querying the table data, we will need an error type similar to the following code:
- Enum Daoerror:errortype {
- Case NoData
- Case Primarykeynull
- }
NoData indicates that there is no data condition, andprimarykeynull indicates that the table's primary key (Primary key) is empty.
Then we can catch the error with the following code.
- do {
- Try to access a data table function or method
- } catch Daoerror.nodata {
- Print ("no data.") ")
- } catch Daoerror.primarykeynull {
- Print (the primary key is empty.) ")
- }
A function or method that can be placed behind a try is required, and they are likely to throw an error, which is appended with the throws keyword after the arguments to the function or method declaration , indicating that the function or method can throw an error.
The example code for declaring a throw error method is as follows:
[HTML]View PlainCopyprint?
- Delete Note Recording method
- Func Remove (model:note) throws {
- ...
- }
- Querying all record Data methods
- Func FindAll () throws-> [Note] {
- ...
- }
The above code remove (_:) method has no return value, and thethrows keyword is placed after the parameter. FindAll () has a return value of throws keyword 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:
Throws an error artificially through a throw statement in a function or method .
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:
[HTML]View PlainCopyprint?
- Delete 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 keys are equal
- For (index, note) in Listdata.enumerate () where note.date = = Date {
- Listdata.removeatindex (Index)
- }
- }
- Querying 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 throw error
- Let datas = try FindAll ()
- For note in Datas {
- Print ("Date: \ (note.date!) -Content: \ (note.content!) ")
- }
- }
- Try PrintNotes ()
The Guard statement is best at dealing with this early judgment, which throws an error when the condition is false.
The FINDALL () statement itself is likely to produce an error, but it is not captured and processed using a catch statement, which causes the error to propagate to the caller of the function or method, and if neither of its callers captures processing, the last program will have a run-time error.
Swift-do-try-catch error Handling Mode-standby