Swift-do-try-catch error Handling Mode-standby

Source: Internet
Author: User

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.

 
    1. Let contents = nsstring (contentsoffile:filepath,
    2. Êencoding:nsutf8stringencoding, Error:nil)//error parameter pass a nil

Or

 
    1. var err:nserror?
    2. Let contents = nsstring (contentsoffile:filepath,
    3. ê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:

 
  1. Import Foundation
  2. Do {//to do some action
  3. Let str = try NSString (Contentsoffile:filepath,
  4. êencoding:nsutf8stringencoding)//What to try to do
  5. } catch let err as nserror {//Enter catch code block if failed
  6. Err.Description
  7. }

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:

 
    1. do {
    2. Try Statement
    3. Successfully working with statement groups
    4. } catch match Error {
    5. Error Handling Statement Group
    6. }

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:

 
    1. Enum Daoerror:errortype {
    2. Case NoData
    3. Case Primarykeynull
    4. }

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.

 
      1. do {
      2. Try to access a data table function or method
      3. } catch Daoerror.nodata {
      4. Print ("no data.") ")
      5. } catch Daoerror.primarykeynull {
      6. Print (the primary key is empty.) ")
      7. }
  1. 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?
      1. Delete Note Recording method
      2. Func Remove (model:note) throws {
      3. ...
      4. }
      5. Querying all record Data methods
      6. Func FindAll () throws-> [Note] {
      7. ...
      8. }

    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?
      1. Delete Note method
      2. Func Remove (model:note) throws {
      3. Guard Let date = Model.date else {//judgment thrown when there is a guard statement
      4. Throw "PRIMARY key is empty" error
      5. Throw Daoerror.primarykeynull
      6. }
      7. Compare date primary keys are equal
      8. For (index, note) in Listdata.enumerate () where note.date = = Date {
      9. Listdata.removeatindex (Index)
      10. }
      11. }
      12. Querying all data methods
      13. Func FindAll () throws-> [Note] {
      14. Guard Listdata.count > 0 Else {//judgment thrown when there is a guard statement
      15. Throws "No data" error.
      16. Throw Daoerror.nodata
      17. }
      18. Return ListData
      19. }
      20. Func PrintNotes () throws {//Declaration throw error
      21. Let datas = try FindAll ()
      22. For note in Datas {
      23. Print ("Date: \ (note.date!) -Content: \ (note.content!) ")
      24. }
      25. }
      26. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.