The program may produce various unexpected exceptions when running, such as insufficient disk, insufficient memory, or overflow of mathematical operations, such as an array out of bounds. To solve these problems, C + + provides an exception handling mechanism, which is typically composed of try statements and catch statements.
One, try and catch statements
The sample code is as follows:
First we define a function to divide and throw an exception if dividend equals zero. You can see that the definition of the function is followed by a throw (int) statement, which is used to emphasize that this function throws an int type exception, and of course it is not possible to throw various types. When we enter B as zero, Cal throws 0, and there is no catch statement inside the CAL function to catch the exception, so the CAL function stops. The exception that is thrown by the Cal function is caught in the main function by a catch statement (noting that catch (int) represents the throw of the catch int type, and that we can use multiple catch to catch multiple types of exceptions at the same time), the code block within the catch is executed. Of course, if we throw a double type in the Cal function, the catch of the main function cannot be captured and the program crashes directly. That is, the type thrown by the throw is consistent with the type that the catch can catch. The result of the code operation is as follows:
If we call several functions in succession, when the bottom function throws an exception, it will first look for the catch statement in itself, and if the catch cannot be completed, it will throw the exception to the function that called it, and if not, continue to throw up, and so on ..., this is the exception stack expansion:
Second, the Exception class
If we just throw an int type, we just know that there is an exception thrown and can't know more information. But if we just throw a class, we can add a lot of information to the class. such as the following code:
1#include <bits/stdc++.h>2 using namespacestd;3 4 classmyexception{5 Private:6 Char*s;7 Public:8MyException (Char*_s) {9s =_s; Ten }; One Char*What () { A returns; - } - the - }; - DoubleCalDoubleADoubleb) { - if(b = =0)ThrowMyException ("B is 0"); + if(A = =0)ThrowMyException ("A is 0"); - returnAb; + } A intMainintargcChar Const*argv[]) at { - DoubleA, B; - while(Cin >> a >>b) { - Try{ -cout << Cal (A, B) <<Endl; - } in Catch(MyException &e) { -cout << e.what () <<Endl; to } + } - return 0; the}
We define an exception class that, when an exception is generated, can be called by the constructor to pass the exception information to the data member S, which can then be called by the member function what () to output the exception information when caught. The results of the program run as follows:
End.
C + + exception mechanism