C ++ Exception Handling

Source: Internet
Author: User

Errors in a program are divided into compile-time errors and runtime errors. Errors during compilation are mainly caused by syntax errors, such as NO plus points at the end of a sentence, mismatched parentheses, and keyword errors. Such errors are easier to modify, because the compilation system will point out the number of errors in the first line and what errors. Errors During running are not easy to modify, because errors are unpredictable or predictable but unavoidable, such as insufficient memory space or function calls, an array out-of-bounds error occurs. If you do not take effective preventive measures for these errors, you will often fail to get the correct running result, and the program may not be terminated normally or cause serious crashes. We collectively refer to errors during program running as exceptions, and exception handling as exception handling. The exception handling mechanism provided in C ++ has a clear structure, ensuring program robustness to a certain extent.

The exception handling process in C ++ is as follows: when an exception occurs in the execution program, it can be not handled in this function, but an error message is thrown, pass it to the upper-level function to solve the problem. If the upper-level function cannot be solved, it will be passed to the upper-level function for processing. If the upload fails to be processed at the highest level, the running system automatically calls the system function terminate and calls abort to terminate the program. This exception handling method separates the exception triggering and processing mechanism, rather than processing it in the same function. This makes the underlying function only need to solve the actual task, instead of having to consider handling the exception too much, and then hand over the exception handling task to the previous function for processing.

The exception handling mechanism of C ++ consists of three parts: Try (check), throw (throw), and catch (catch ). Put the statement to be checked in the try module. Check whether an error occurs in the statement. Throw throws an exception and sends an error message. Catch will capture the exception information and handle it. Generally, the exception thrown by throw must match the exception type caught by catch. The general format of exception handling is:

Try

{

Check statement

Throw exception

}

Catch (exception type 1)

{

Statement 1 for Exception Handling

}

Catch (exception type 2)

{

Statement 2 for Exception Handling

}

...

The following is an example of exception handling:

1 # include "stdafx. H"
2 # include <iostream>
3
4 template <typename T>
5 t Div (t x, t y)
6 {
7 if (y = 0)
8 throw y; // throw an exception
9 return x/y;
10}
11
12 INT main ()
13 {
14 int x = 5, y = 0;
15 double X1 = 5.5, Y1 = 0.0;
16 try
17 {
18 // The statement to be checked
19 STD: cout <x <"/" <Y <"=" <Div (x, y) <STD: Endl;
20 STD: cout <X1 <"/" <Y1 <"=" <Div (x1, Y1) <STD: Endl;
21}
22 catch (INT) // exception type
23 {
24 STD: cout <"The Division is 0. calculation error! "<STD: Endl; // Exception Handling statement
25}
26 catch (double) // exception type
27 {
28 STD: cout <"The Division is 0.0. calculation error! "<STD: Endl; // Exception Handling statement
29}
30
31 return0;
32}

Result:

After reading the sample code above, someone may ask, the second double-precision Division calculation should also throw an exception. This is not the case in the actual running process, in fact, this double-precision division function has not been executed at all. The execution procedure of the preceding program is as follows: An exception occurs when the function Div (X, Y) is called. The "Throw y" statement in the function Div throws an exception and does not execute return x/y, catch catch the int type exception and handle the exception, and then directly execute "Return 0 ". Therefore, the div (x1, Y1) and catch (double) {} modules are not executed at all. If we change the value of Y to 1, the result is:

If no exception occurs during the execution of the try Statement module, the catch statement block does not take effect and the process is transferred to the subsequent statement for further execution. From the above two results, we can see that the int type thrown by the first throw finds the catch to process this type, and the second throw the double type finds the catch to process the double type.

The following are some additional points for exception handling: (1) Try and catch blocks must be enclosed in curly brackets, even if there is only one statement in the curly brackets, curly brackets cannot be omitted; (2) try and catch must appear in pairs. Only one try block can be found in a try_catch result, but multiple catch blocks can be found to match different exception information. (3) if no exception information type is specified in the Catch Block, use the delete node number "... ", it indicates that it can capture any type of exception information; (4) if throw does not include any expression, it indicates that it throws the exception information currently being processed, (5) once an exception is thrown in C ++, if the program does not have any capture, the system will automatically call a system function terminate, it calls abort to terminate the program;

Finally, I will use an example to summarize what we are talking about today (Development Tool: vs2010 ):

View code

1 # include "stdafx. H"
2 # include <iostream>
3
4 template <typename T>
5 t Div (t x, t y)
6 {
7 if (y = 0)
8 throw y; // throw an exception
9 return x/y;
10}
11
12 INT main ()
13 {
14 int x = 5, y = 1;
15 double X1 = 5.5, Y1 = 0.0;
16 try
17 {
18 // The statement to be checked
19 STD: cout <x <"/" <Y <"=" <Div (x, y) <STD: Endl;
20 STD: cout <X1 <"/" <Y1 <"=" <Div (x1, Y1) <STD: Endl;
21}
22 catch (...) // catch any type of exception
23 {
24 try
25 {
26 STD: cout <"any type exception! "<STD: Endl;
27 throw; // throw the current exception information to the previous catch
28}
29 catch (INT) // exception type
30 {
31 STD: cout <"Division: 0. calculation error! "<STD: Endl; // Exception Handling statement
32}
33 catch (double) // exception type
34 {
35 STD: cout <"The Division is 0.0. calculation error! "<STD: Endl; // Exception Handling statement
36}
37
38}
39
40 return0;
41}

Result:

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.