The basic idea of exception handling in C + + and the use _c language of throw statement throw exception

Source: Internet
Author: User
Tags anonymous error handling exception handling throw exception

The basic idea of exception handling
The basic idea of the exception handling of C + + can be summarized as the traditional error handling mechanism and the function return value to handle the error.

1 The exception handling mechanism of C + + makes exception and exception handling not in the same function, so that the underlying function can focus on solving specific problems, without too much consideration of abnormal processing. Upper-level callers can then design the handling of different types of exceptions in a suitable location.
2 The exception is specifically directed against a series of errors in abstract programming, 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 encountered error message will want to go to a number of levels above to try again, as shown

3) The anomaly is detached from the function mechanism, which determines the leaping back-jump of the function.
4) Exception spanning function

Exception Basic Syntax

1 if there is an exception, the throw operation creates an exception object and throws it.
2 Embed the program segment that may throw an exception in a try block. Control arrives at the try statement in the normal order, and then executes the protection segment within the try block.
3 If no exception is caused during the protection segment execution, the catch clause following the try block is not executed. The statement that follows the last catch clause following the TRY block continues to execute.
4 The Catch clause is checked in the order in which it appears after the try block. A matching catch clause will catch and handle the exception (or continue throwing the exception).
5 If a matching processor is not found, the run function terminate is called automatically, and its default function is to invoke the abort termination program.
6 cannot handle the exception, can be in the last branch of catch, use throw syntax, throw up
7 The exception mechanism and function mechanism do not interfere with each other, but the way to capture is based on type matching. Capturing corresponds to a function return type rather than a matching function parameter, so capturing does not take into account a variety of data type matching issues in a throw.
A catch code block must appear after a try, and multiple catch blocks can appear after a try block to catch various types of throws.
The exception mechanism is based on the principle that the program operation is essentially a data entity doing some operations, so the occurrence of anomalies, it must be an entity out of error, the corresponding data type of the entity as the basis for throwing and capturing.
8) exception capture strictly according to the type match
The severity of the type matching of the exception captures can match the type of the template, and it does not allow implicit conversions of compatible types, for example, the cast 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" OK. "Prompts to exit after an exception has occurred

int main () { 
  try{ 
    throw ' H '; 
  } 
  catch (int) { 
    cout << "int exception.\n"; 
  } 
  cout << "That ' s ok.\n"; 
 
  return 0; 
} 

When the

stack Chene (unwinding)
exception is thrown, all objects that are constructed on the stack are automatically refactored from the entry to the try block until the exception is thrown. The order of the destructor is the opposite of the Order of construction. This process is called a stack of Chene (unwinding).

#include <iostream> #include <cstdio> using namespace std; 
 
Class MyException {}; 
    Class Test {public:test (int a = 0, int b = 0) {this->a = A; 
    This->b = b; 
  cout << "Test constructor executes" << "A:" << a << "B:" << b << Endl; 
  } void Printt () {cout << "a:" << a << "B:" << b << Endl; 
  } ~test () {cout << "Test destructor executes" << "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 test stack variables are reconstructed after the exception is thrown" << Endl; 
throw MyException (); When the int main () {//exception is thrown, from entering the try block, until the exception is thrown, all the objects that are constructed on the stack during this period//will be automatically destructor. 
  The order of the destructor is the opposite of the Order of construction. 
  This process is called the Stack's Chene (unwinding) try {myFunc (); //catch (myexception &e)//Here cannot access exception object catch (myexception)//You cannot access the exception object {cout << received the MyException class Type Exception ";< Endl; 
  catch (...) 
  {cout << "unknown type exception" << Endl; 
return 0; 

 }

Exception Interface Declaration
1 in order to enhance the readability of the program, you can list any 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 the function declaration does not contain an exception interface 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 its exception interface declaration is not allowed to throw, the unexpected function is invoked, and the function default behavior calls the Terminate function to abort the program.

Traditional processing errors

#include <iostream> 
#include <cstdio> 
using namespace std; 
 
Traditional error handling mechanism 
int mystrcpy (char *to, char *from) 
{ 
  if (from = = NULL) {return 
    1; 
  } 
  if (to = = NULL) {return 
    2; 
  } 
 
  Copy when the scene check 
  if (*from = = ' a ') {return 
    3;//Copy Error 
  } while 
  (*from!= ' ") { 
    *to = *from;
   to++; 
    from++; 
  } 
  *to = ' n '; 
 
  return 0; 
} 
 
int main () 
{ 
  int ret = 0; 
  Char buf1[] = "ZBCDEFG"; 
  Char buf2[1024] = {0}; 
 
  ret = mystrcpy (buf2, buf1); 
  if (ret!= 0) { 
    switch (ret) {case 
    1: 
      cout << "source buf error!\n"; 
      break; 
    Case 2: 
      cout << "Purpose buf error!\n"; 
      break; 
    Case 3: 
      cout << "copy process error!\n"; 
      break; 
    Default: 
      cout << "Unknown error!\n"; 
      break; 
    } 
  } 
  cout << "buf2:\n" << buf2; 
  cout << Endl; 
 
  return 0; 
} 

Throw char*

#include <iostream> 
#include <cstdio> 
using namespace std; 
 
Throw char * 
void mystrcpy (char *to, char *from) 
{ 
  if (from = = NULL) { 
    throw "source buf error"; 
  } 
  if (to = = NULL) { 
    throw "buf error"; 
  } 
 
  Copy-time scene check 
  if (*from = = ' a ') { 
    throw "copy process error";//Copy Error 
  } while 
  (*from!= ' ") { 
    *to = *f Rom; 
    to++; 
    from++; 
  } 
  *to = ' n '; 
 
  return; 
} 
 
int main () 
{ 
  int ret = 0; 
  Char buf1[] = "ABCDEFG"; 
  Char buf2[1024] = {0}; 
 
  Try 
  { 
    mystrcpy (buf2, BUF1); 
  } 
  catch (int e)//E can write without writing 
  { 
    cout << e << "int type exception" << Endl; 
  } 
  catch (char *e) 
  { 
    cout << "char* type exception" << Endl; 
  } 
  catch (...) 
  { 
  }; 
  cout << Endl; 
 
  return 0; 
} 

Throw class object

#include <iostream> 
#include <cstdio> 
using namespace std; 
 
Class Badsrctype {}; 
Class Baddesttype {}; 
Class Badprocesstype 
{public 
: 
  badprocesstype () 
  { 
    cout << "Badprocesstype constructor do \ n"; 
  } 
 
 
  badprocesstype (const badprocesstype &obj) 
  { 
    cout << ' badprocesstype copy constructor do \ n '; 
  } 
 
  ~badprocesstype () 
  { 
    cout << "Badprocesstype destructor do \ n"; 
  } 
 
}; 


Throw class object, type exception

void My_strcpy3 (char *to, char *from) {if (from = = NULL) {throw badsrctype (); 
  } if (to = = NULL) {throw baddesttype (); 
    //copy is the scene check if (*from = = ' a ') {printf ("Start badprocesstype type exception \ \"); Throw Badprocesstype (); 
  Will it produce an anonymous object? 
  } if (*from = = ' B ') {Throw & (Badprocesstype ());//Will an anonymous object be generated? 
  } if (*from = = ' C ') {throw new Badprocesstype;//Will an anonymous object be generated? 
    while (*from!= ' ") {*to = *from; 
    to++; 
  from++; 
} *to = ' I '; 
  int main () {int ret = 0; 
  Char buf1[] = "CBBCDEFG"; 
 
  Char buf2[1024] = {0}; 
    try {//my_strcpy1 (buf2, BUF1); 
    My_strcpy2 (Buf2, BUF1); 
  My_strcpy3 (Buf2, BUF1); 
  The catch (int e)//e can write or do not write {cout << e << "int type exception" << Endl; 
  The catch (char *e) {cout << e << "char* type exception" << Endl; //---catch (badsrctype e) {cout << "BadsrctypType E exception "<< Endl; 
  catch (Baddesttype e) {cout << "Baddesttype type exception" << Endl;  
  //CONCLUSION 1: Copy constructs an exception variable if an exception variable is used when it is accepted. 
  /* catch (Badprocesstype E)//is the anonymous object copy to E or E or that anonymous object {cout << "Badprocesstype type exception" << Endl;  /* Conclusion 2: Use the reference to use the Throw object catch (Badprocesstype &e)//Is the anonymous object copy to E or E or that anonymous object {cout << 
  "Badprocesstype type anomaly" << Endl; //Conclusion 3: Pointers can be written with references/elements but references and elements cannot be written in a catch (Badprocesstype *e)//Is the anonymous object copy to E or E or the anonymous object {cout &L 
    t;< "Badprocesstype type anomaly" << Endl; 
  Delete e; 
  }//Conclusion 4: When class objects are used, references are appropriate//-catch (...) 
  {cout << "unknown type exception" << Endl; 
return 0; 
 }


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.