Exception handling mechanism

Source: Internet
Author: User

1) anomaly is a program control mechanism, independent and complementary to the function mechanism

function is a program control system that is connected with the upper and lower functions of the stack structure, the exception is another control structure, it is attached to the stack structure, but can set multiple exception types as the net catching condition, thus jumping back in the stack mechanism by type matching.

2) Abnormal design Purpose:

Stack mechanism is a highly rhythmic control mechanism, object-oriented programming requires a directional, purposeful control drive between objects, from the beginning, the anomaly is directed at changing the program structure to adapt to the object-oriented program to work more effectively this topic, rather than just for error handling.

First, the basic idea of exception handling:

1) The exception handling mechanism of C + + makes exception's throwing and exception handling unnecessary in the same function, so that the underlying function can focus on solving the specific problem without too much consideration of exception handling. Upper-level callers can then design the handling of different types of exceptions in the appropriate location.

2) exception is specifically for the abstract programming of a series of error handling, C + + can not rely on the function mechanism, because the nature of the stack structure is advanced, and then access, can not jump, but the characteristics of error handling is to encounter the error message you want to go to a number of levels to retry,

3) The anomaly is detached from the function mechanism, which determines the leap-back of the function.

4) exception spanning function.

Implementation of C + + exception handling

Exception Basic Syntax

1) If an exception is thrown, an exception object is created and thrown by the throw operation.

2) Embed the program segments that may throw exceptions in the try block. Control reaches the try statement through normal sequential execution, and then executes the protection segment within the try block.

3) If no exception is raised during the protection segment execution, then the catch clause following the try block is not executed. The program proceeds from the statement following the last catch clause following the try block.

4) The catch clause is checked in the order in which it appears after the try block. The matching catch clause will catch and handle the exception (or continue throwing the exception).

5) If the matching processor is not found, the run function terminate will be called automatically, and its default function is to call abort to terminate the program.

6) cannot handle the exception, can be in the last branch of the catch, using the throw syntax, throw up.

Case 1: Divisible by zero case int divide (int x, int y) {if (y ==0) {throw x;} return x/y;} void Main () {try{cout << "8/2 =" << Divide (8, 2) << endl;cout << "10/0 =" << Divide (10, 0) & lt;< Endl;} catch (int e) {cout << "E" << "is divided by zero!" << Endl;} catch (...) {cout << "Unknown exception" << Endl;} cout << "OK" << Endl; System ("pause"); return;}

  

Case 2:class a{};void F () {  if (...) throw A;} void G () {  try{    f ();  } catch (B) {    cout<< "exception b\n";  }} int main () {  g ();}

Analytical:

Throw a will penetrate the function f,g and main to reach the last line of defense of the system--to excite the Terminate function.

The function calls the abort function that caused the run to terminate.

The function of the last line of defense can be set by the programmer. thereby stipulating the Act before its termination.

To modify the system default behavior:

1. You can modify the default processor that cannot catch an exception by using the Set_terminate function, which is handled by a custom function when there is no catch exception:

2.void myterminate () {cout<< "hereismyterminate\n";}

3.set_terminate (myterminate);

The 4.set_terminate function is declared in the header file exception, and the parameter is the function pointer void (*) ().

7) Exception mechanism and function mechanism do not interfere with each other, but the way of capturing is based on type matching . Snapping matches the function return type rather than matching function parameters, so snapping doesn't have to consider multiple data type matching issues in a throw

Like what:

Class A{};class B{};int Main () {Try{int j = 0;    Double d = 2.3;    Char str[20] = "Hello";cout<< "Please input a exception number:"; int A; Cin>>a;switch (a) {case  1:throw D;      Case  2:throw J;      Case  3:throw str;case  4:throw A ();      Case  5:throw B ();d efault:cout<< "No throws here.\n";    } catch (int) {cout<< "int exception.\n";} catch (double) {cout<< "Double exception.\n";} catch (char*) {cout<< "char* exception.\n";} catch (a) {cout<< "class A exception.\n";} catch (b) {cout<< "Class B exception.\n";} cout<< "That ' s ok.\n"; system ("Pause");}

Analytical:

The catch code block must appear after the try, and multiple catch code blocks can appear after the try block to catch a variety of different types of throws.

Exception mechanism is based on the principle that the program is essentially a data entity in doing some operations, so the occurrence of anomalies, it must be an entity has gone wrong, the entity corresponding to the data type as the basis for throwing and capturing .

8) exception catching is strictly matched by type

The severity of the type matching of an exception capture can be comparable to the type of template, which does not allow implicit conversions of compatible types; For example, the throw char type is not captured with the int type.

For example, the following code does not output "int exception.", and thus does not output "that's OK." Prompt to exit because an exception occurred.

int main () {

try{

Throw ' H ';

}

catch (int)

{

cout<< "int exception.\n";

}

cout<< "That ' s ok.\n";

}

Stack unwinding (unwinding)

When an exception is thrown, all objects that are constructed on the stack are automatically refactored from the time it enters the try block to the exception being thrown. The order of the destruction is the opposite of the Order of construction. This process is called the unwinding of the stack (unwindingclass myexception {}class Test{

Public:test (int a=0, int b=0) {this->a = A;this->b = B;cout << "Test constructor Execution" << "A:" << a << "B:" << b << endl;} void Printt () {cout << "a:" << a << "B:" << b << endl;} ~test () {cout << "Test destructor Execution" << "A:" << a << "B:" << b << endl;} Private:int a;int b;}; void MyFunc () throw (myexception) {Test T1; Test T2;cout << "defines two stack variables, how the stack variable is refactored after an exception is thrown" << endl;throw myexception ();} void Main () {///exception is thrown, from entering the try block, until the exception is thrown, all objects constructed on the stack during this period,//will be automatically destroyed. The order of the destruction is the opposite of the Order of construction. This process is called the stack of unwinding (unwinding) try {myFunc ();} catch (MyException &e)//Cannot access exception object catch (MyException)//Here cannot access exception object {cout << "received MyException type exception" << Endl;} catch (...) {cout << "unknown type exception" << Endl;} System ("pause"); return;}

  

Exception Interface Declaration

1) in order to enhance the readability of the program, you can list all the exception types that may be thrown in the function declaration, for example:

void Func () throw (A, B, C, D); This function func () can and can only throw exceptions of type a B C D and its subtypes .

2) If an exception interface declaration is not included in the function declaration, the secondary function can throw any type of exception, for example:

void Func ();

3) A function that does not throw any type of exception can be declared as:

void Func () throw ();

4) If a function throws an exception that is not allowed by its exception interface declaration, the unexpected function is called, and the function default behavior calls the Terminate function to abort the program.

Exception handling mechanism

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.