Snoop on Swift programming error handling and exception throw, and snoop on swift

Source: Internet
Author: User
Tags case statement

Snoop on Swift programming error handling and exception throw, and snoop on swift

In Swift 2.0, the Swift language has made a new design for its error handling. Of course, the re-design results make it easier to use the error handling system. The topic of today's blog is to systematically handle errors in Swift and how exceptions are thrown in Swift. In compiled languages, errors are generally divided into compilation errors and runtime errors. The errors we handle in the Code are runtime errors. The purpose of exception handling is to prevent other side effects caused by program errors, for example, user data is not saved.

In today's blog, we will first show several situations where exceptions are actively generated, and then how to handle them.

I. Active exit of the program

In Objective-C, we use assertions during unit tests. Exceptions are generated when conditions in assertions are met, and corresponding asserted errors are printed, there are also several syntax exceptions in Swift. These methods are provided in the first part of this blog.

1. Fatal Errors (Fatal error)

You can use the fatalError () function to terminate your application immediately and provide the termination information in fatalError. Using the fatalError () function will terminate your application without any conditions. It is easy to use, that is, a function call. The Demo below is clear, so I will not repeat it too much here.

 

2. Assertions (Assertions)

Assertions are indispensable in unit tests. The difference between assertions in Swift and Objective-C is not great, and the usage is similar. The following are two methods of assertion. We can see from the code prompts that the prompt conditions in assertion are optional. Assertions work in Debug mode, but are ignored in the Release version.

 

In the assert () function, the first parameter is of the Bool type, and the second parameter is the output information. When the condition is true, the assertion is not executed, and the corresponding assertion information is not printed. When the condition is false, the assertion is executed and the corresponding assertion information is printed.

 

The assertionFailure () function has only one Message parameter, which can be omitted. assertionFailure () has no condition. As follows:

 

3. Prerequisites)

Preconditions is used in the same way as assertion, but it is important that Preconditions will be executed in both debug and release modes unless compiled using-Ounchecked. Below is a prompt for the Preconditions function provided by the code prompt, as shown below:

For the specific usage of Preconditions, refer to assertions. Like assertions, we will not repeat them too much here.

 

Ii. handle errors in Swift

In Objective-C, if you have handled errors, you will be familiar with NSError. In Swift, if you want to define your own error type, you only need to implement the ErrorType protocol. After declaring the error type, you can use the custom error type when handling the error throw exception. The following will take you through the process of handling errors in Swift step by step.

1. Use enumeration to create error types

(1). Follow the ErrorType protocol to customize the error type. An Error Type enumeration is defined below, which complies with the ErrorType protocol. In the following code, we will use the MyCustomErrorType enumeration. The implementation of the error enumeration is as follows:

123456 // Define the Error Type enum MyCustomErrorType: ErrorType {case ErrorReason1 case ErrorReason2 case ErrorReason3}

(2 ). in our function definition, we can use the throws keyword and throw the error in the function. The error type can be used as defined above. The function below is a function that can throw an error. The thrown error is the type defined in the above enumeration. The Code is as follows:

12345678 Func myThrowFunc1 () throws {let test: Int? = Nil guard test! = Nil else {throw MyCustomErrorType. ErrorReason1 }}

(3). The function above throws an error. Next, use do-catch to handle the thrown error. Use try to capture errors and do-catch to process errors. The specific processing method is as follows. The error handling below is similar to the switch-case statement. The type of matching error can be enumerated after catch, as shown below:

 

(4) In enumeration implementation error types, we can add error codes and causes for errors by binding values. When declaring enumeration, we use the enumeration element value binding feature (for more information about enumeration, refer to previous blog "snoop on different enumeration types of Swift"). When declaring the enumerated member ErrorState, we bind two variables to it: the error code errorCode and the error cause errorReason. The two can be used to input corresponding values when an error is thrown, as shown in the throwError function in the following code snippet. When an error is thrown, the error code specified for errorCode is 404, the error cause specified for errorReason is "not found ".

Finally, we used do-catch to handle exceptions. In catch, we obtained the bound error code and cause, and filtered the error code through the where clause. The catch usage here is the same as that for obtaining enumeration bound values in switch-case, so we will not repeat it too much here. The specific implementation method is as follows:

 

2. Use struct to add Reason for error handling

In the above content, the enumeration follows the ErrorType protocol to define a specific error type. Next, we will use struct to follow the ErrorType protocol and add error causes for the error type. That is to say, when an error is thrown, we can provide the error cause for the custom error type. This function is very commonly used in development, and it is also very easy to use. Next, let's take a look at how to add error causes for our error types.

(1) Create an error type using struct. The struct named MyErrorType below follows the ErrorType protocol and declares a reason constant in the MyErrorType struct, the reason constant stores the error cause. The specific implementation method is as follows:

123 Struct MyErrorType: ErrorType {let reason: String}

(2) After the Error Type struct is defined above, it can be used in error throw. When an error is thrown, you can specify the cause of the error as follows:

12345678 Func myThrowFunc2 () throws {let test: Int? = Nil guard test! = Nil else {throw MyErrorType (reason: "I am a detailed error cause, stored in error ")}}

(3) At last, do-catch must be performed on the thrown error. during processing, you can print the cause of the error. The cause of the error is stored in the error, the specific operations and printed results are as follows:

According to the above output, error is our custom MyErrorType type. We can use the following code to replace the print statement in catch, as shown below:

 

The above practice seems a little troublesome. Another method to simplify the output is to implement the CustomDebugStringConvertible protocol in the above struct and rewrite the description information so that when an error is printed, only the error message is printed. The structure after rewriting is shown below.

123456 1 struct MyErrorType: ErrorType, CustomDebugStringConvertible {2 let reason: String3 var debugDescription: String {4 return "Error Type ----- (self. dynamicType): (reason)" 5} 6}

After the modification, the output result is as follows. The error message rather than the MyErrorType type is printed directly.

 

3. Enable the String type to follow the ErrorType protocol and use the String directly to provide the error cause

In "2", we use a struct that follows the ErrorType protocol to provide error information for errors. In the following section, we will provide error information for the thrown error in a simpler way. This method is simpler and easier to understand, as shown in the following code:

 

3. Use built-in keywords in error handling

1. explore these built-in keywords

Some built-in keywords (_ FILE __, _ FUNCTION __, _ LINE _) are provided in Swift to obtain context information. In the third part of this blog, it will show how to use these built-in keywords in our error handling. The following describes the functions of these built-in keywords:

The built-in keywords mentioned above are actually macro definitions for storing the code context. The code snippet above briefly provides the functions and usage of these built-in keywords. These built-in keywords will be used in ErrorType in the next step, make our error messages more colorful.

 

2. Use the preceding built-in keywords in ErrorType

To use these built-in context keywords in ErrorType, we only need to extend ErrorType so that it can provide error context information when ErrorType provides error information. Of course, this implementation is relatively simple, that is, a contextString () Extension Method is added to ErrorType (). The function of this method is to provide the error context information, that is, to call the contextString () method to generate the context description in the case of an error. The specific extension implementation of the ErrorType protocol is as follows.

In the code snippet below, we expanded ErrorType and added the contextString function implementation for ErrorType. The contextString () function has three default parameters: file-current file name, function-current error function name, and line-the number of lines currently throwing an exception. The preceding three parameters have their default values _ FILE __, _ FUNCTION __, and _ LINE __. The return value of this extended function is the string information composed of the three parameters. The specific implementation is as follows:

 

3. Use the extended contextString Method

The preceding Code uses struct to implement the ErrorType protocol and adds the error cause for the error type. Next, we will use the contextString () function to add description information while adding a reason. The CustomErrorType struct below follows the ErrorType Protocol. A reason constant is added to store the error cause, a context constant to store the context information, and a constructor is added to the constructor, initialize the reason constant in the constructor. The specific implementation is as follows:

 

4. Throw and catch exceptions

In the code below, the throwError () function throws an exception. The error type is mermerrortype. When creating a CustomErrorType instance, that is, the err variable, we specify the error cause, that is, assign a value to the reason. After creating the err instance, we call the extended contextString () function to obtain the context information of the exception and store the returned content in the context attribute of the err instance. Finally, use the throw keyword to throw the err instance, as shown in the first part of the code below.

After creating a function that throws an exception, we need to capture the thrown exception. That is, use try to capture exceptions and do-catch to handle exceptions. The specific operations are as follows.

 

5. Analyze and print the results

After the above steps, if you perform a test in Playground, you will see the following information on the console. From the printed information, we can see that the information includes reason: Error cause, and context: exception context. In the output result below, we can see that this is not the exact file name, because it is used in Playground and is not the exact Swift source file, therefore, the exact file name cannot be obtained.

To observe the exact file name, we need to throw the above exception in the exact Swift source file. In a specific Swift source file, we will see the output below. From the output log below, we can clearly see that the file name is a detailed file path. As follows:

 

Q: one-click call to programmer Q & A artifacts, one-to-one service, developer programming required official website: www.wenaaa.com

QQ Group 290551701 has gathered many Internet elites, Technical Directors, architects, and project managers! Open-source technology research, welcome to the industry, Daniel and beginners interested in IT industry personnel!

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.