Prying into error handling and exception throwing _swift in Swift programming

Source: Internet
Author: User
Tags case statement constant error code error handling function definition

In Swift version 2.0, the Swift language has a new design for its error handling, and, of course, the redesigned result makes the error-handling system more fun to use. The topic today is to systematically engage in Swift's error handling and see how the exception is thrown in Swift. In a compiled language, errors are generally divided into compilation errors and run-time errors. The error we normally handle in our code is a run-time error, and the purpose of our handling of the exception is to prevent errors in the program from causing other side effects, such as the user data not being saved, and so on.

In today's article, we first give several cases of active exception, and then give a way to deal with the passive exception.

I. Several cases of active withdrawal procedure

In Objective-c, we use assertions in unit tests where the conditions in the assertion produce an exception and print out the corresponding assertion error, and there are several syntax in swift that produce an exception. These methods are given in the first part of this blog.

1.Fatal Errors (fatal error)

You can terminate your application immediately by using the FatalError () function, and you can give the termination information in FatalError (). Using the FatalError () function, you will terminate your application without conditions, and it is simpler to use a function call. Below this demo at a glance, this will not do too much to repeat.


2. Assertions (asserted)

There is no assertion in unit testing, and the difference between assertions and objective-c in Swift is not too great and the use of methods is similar. Below is the two methods of assertion, which are known by the code hints that the prompt condition in the assertion is optional. Assertions work in debug mode, but are ignored in release versions.


In the Assert () function, the first argument is the bool type, and the second parameter is the output information. When the condition is true, the assertion is not executed and the appropriate assertion information is not printed. When the condition is false, the assertion executes, and the appropriate assertion information is printed.


The Assertionfailure () function has only one message argument, and the parameter can also be omitted, assertionfailure () has no condition. As shown below:


3. Prerequisites (Preconditions)

Preconditions's usage and assertions are the same, but there is a major need to preconditions in debug and release mode, unless compiled using –ounchecked. The screenshot below is a hint of the preconditions function given by the code hint, as follows:

For specific uses of preconditions, refer to assertions, as assertions use, and do not repeat them here.

Two. Error handling 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 type of error, you only need to implement the ErrorType protocol. Once you have declared the type of error, you can use a custom error type when you handle an error throwing an exception. Below will take you step-by-step through the error-handling path in Swift.

1. Use enumerations to create error types

(1). Follow the ErrorType protocol and customize the error type. An enumeration of error types is defined below, which follows the ErrorType protocol, which we will use in the next code, as shown in the following implementation of the error enumeration: Mycustomerrortype

 Define error type
 enum Mycustomerrortype:errortype {case
 Errorreason case
 Errorreason case
 Errorreason
 

(2). You can use the throws keyword in our function definition, and throw the error using the Throw keyword in the function, and the type of error you throw can use the type of error we have defined above. The lower function is a function that throws an error, which is the type we defined in the above enumeration. The specific code looks like this:

 Func Mythrowfunc () throws {let
 test:int? = Nil
 guard Test!= nil else {throw
 mycustomerrortype.errorreason< c11/>}
 }

(3). The function of the above function is to throw the error, then it is time to use Do-catch to handle the thrown error. Use try to catch the error, and use Do-catch to handle the error. The specific processing method is as shown below. Similar to the Switch-case statement in error handling below, catch can enumerate the matching error types, as follows:


(4) In the enumeration implementation error type We can add the error code and the error reason to the error through the form of value binding. When declaring enumerations, we used the attributes of enumeration element value bindings (for more details on enumeration usage, please refer to the previous blog, "prying into the other enumerated types of Swift"). When declaring an enumeration member ErrorState, we bound it with two variables, one is the error code errorcode and the other is the error reason Errorreason. The two can pass in the appropriate value when an error is thrown, as shown in the ThrowError function in the code snippet below, where the error code specified for ErrorCode is 404, and the error specified for Errorreason is "not found".

The last thing to do is to use Do-catch to handle the exception, to get the bound error code and the cause of the error in the catch, and to filter the error code through the WHERE clause. The usage of the catch here is the same as that used in Switch-case to get the enumeration bound value, so there is no excessive detail here. The implementation method is shown in the following code:


2. Add reason to error handling using the structure body

In the above, a specific type of error is defined by using enumerations to follow the ErrorType protocol. Next we will use the struct body to follow the ErrorType protocol and add the error reason to the error type. That is, we can provide the wrong reason for the custom error type when the error is thrown. This feature is very commonly used in development, and it is also very cool to use. Let's take a look at how to add the error reason to our error type.

(1) using the struct to create the error type, the lower-named Myerrortype structure follows the ErrorType protocol, and in the myerrortype structure, a reason constant is declared, and the reason constant stores the error reason. The specific implementation methods are as follows:

 struct Myerrortype:errortype {let
 reason:string
 }

(2) After the error type structure is defined above, it can be used in the error throw. When the error is thrown, you can pass in an error reason, as shown in the following code:

 Func Mythrowfunc () throws {
 let test:int? = Nil Guard
 Test!= nil else {throw
 myerrortype (reason: "I am a detailed error reason, stored in error ")
 }
 

(3) Finally to the thrown error do-catch processing, in the process, you can print the cause of the error, the reason for the error stored in error, the specific operation and print results as follows:

The output from the above shows that error is our custom Myerrortype type, and we can use the following code instead of the print statement in the catch, as follows:


The above approach seems to have some trouble, there is a way to simplify the output, that is, in the above structure to implement the Customdebugstringconvertible protocol, a description of the information to a rewrite, you can print error, only the wrong message, the following is the rewritten structure.

 struct Myerrortype:errortype,customdebugstringconvertible {let
 reason:string
 var debugdescription:string { Return
 "error type-----\ (self.dynamictype): \ (Reason)"
 }
 

After modification, the output is as follows, and the error output is printed directly, rather than the Myerrortype type.


3. Make the string type conform to the ErrorType protocol and provide the reason for the error directly using string

In "2", we used the form of a struct to follow the ErrorType protocol to provide error information for the error. In the next section, we will provide an error message for the thrown error in a simpler way. This approach is simpler and easier to understand, as shown in the following code:


Iii. using built-in keywords in error handling

1. Explore these built-in keywords

Some of the built-in keywords (__file__, __function__, __line__, etc.) are available in Swift to get contextual information, and in the third part of this blog, we will show you how to use these built-in keywords in our error handling. Below are the functions of these built-in keywords, as follows:

The above mentioned is a built-in keyword, in fact, is stored in the code context of the macro definition, the upper section of the code to give these built-in keyword function and usage, in the next will be used in errortype these built-in keywords, let our error message more colorful.

2. Use the above built-in keywords in errortype

If you want to use these contextual built-in keywords in errortype, we only need to extend the ErrorType to give the contextual information that went wrong when ErrorType provided the error message. Of course, this is easy to implement, is to add an extension method contextstring () in ErrorType. The purpose of this method is to provide contextual information about the error, which is to call the ContextString () method to generate the context description information where the error occurs. The specific extension of the ErrorType protocol is implemented as shown in the following code snippet.

In the code snippet below, we extended the ErrorType to add a contextstring function implementation for ErrorType. The contextstring () function has three default parameters, file--the current file name, function--the name of the function that is currently faulted, line--the number of rows that currently throw an exception. The above three parameters all have parameter default value, corresponding to __file__, __function__, __line__ respectively. The return value of the extension function is composed of these three parameters from the string information. The actual implementation is shown below:


3. Using the extended ContextString method

Above we use the struct body to implement the form of the ErrorType protocol, adding the error reason to the error type. Next we will add the descriptive information using the contextstring () function while adding reason. The lower customerrortype structure follows the ErrorType protocol, where a reason constant is added to store the cause of the error, a context constant to store contextual information, and a constructor is added to the struct body. Initializes and reason constants in the constructor. The actual implementation is shown below:


4. Throw and Catch exceptions

In the lower code, the function ThrowError () throws an exception, and the type of error thrown is customerrortype. When creating an instance of the Customerrortype type, the ERR variable, we specify the cause of the error, which is to assign a value to the reason. After the Err instance is created, we call the extended contextstring () function to get the contextual information of the exception and store the returned content in the context property 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 catch the thrown exception. That is, the exception is captured using a try, and the exception is processed using Do-catch, as shown in the second paragraph of the following code.

    

5. Analyze Print Results

After the above steps if you are experimenting in playground, you will see the following information on the console. From the printed information we can see that the information includes reason: The cause of the error, and the context: exception contexts. In the output below, we can see that the filename is <EXPR> this is not the exact filename because we are using it in playground and not the exact swift source file, so we don't get the exact filename.

To see 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 see clearly that the filename is a detailed file path. As shown below:


About this article to introduce you to the SWIFT programming error handling and exception thrown to introduce to everyone here, later do a small demo, how to use other error handling methods, in giving you a detailed introduction. Thank you for your support to cloud-dwelling community website!

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.