Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ Analysis of C ++ exception mechanism     - Use Oracle Data Guard to complete cross-platform database migration cases (Database)

- CentOS 7.0 running Docker kernel error solution (Server)

- The Linux C truncate function clears the file notes (Programming)

- Linux log management tools Logrotate (Linux)

- Linux see whether there is a hacker program (Linux)

- How to network to share files between Windows, MAC and Linux (Linux)

- C language header file defines a global variable (Programming)

- Linux file permissions bit forced bits and adventure Comments (Linux)

- Windows 7 hard disk to install Ubuntu 14.10 (Linux)

- Linux settings Java_home (Linux)

- Storm basic framework for analysis (Programming)

- MySQL how to export files with the date format (Database)

- MySQL replication master and slave structure built (Database)

- Linux stand-alone OGG synchronous Oracle 11g DB test (Database)

- IOwait Linux system monitoring diagnostic tools (Linux)

- Java MVC CRUD examples (Programming)

- CentOS7 install MySQL5.6.22 (Linux)

- Execute command sentence can result in equipment permanently bricked in Linux laptop (Linux)

- Linux fixes fatal error: x264.h: No such file or directo (Linux)

- Command filter MySQL slow query log (Database)

 
         
  Analysis of C ++ exception mechanism
     
  Add Date : 2018-11-21      
         
       
         
  Text

C ++ exception mechanism Overview

Exception Handling C ++ is a language mechanism for handling abnormal events in the program. Abnormal events are represented as objects in C ++ exception. When an abnormal event occurs, the program throws an exception using the throw keyword expression, throw point is called point exception occurs, the program set up by the operating system the current exception object, and then execute the program of the current exception handling code block contains the exception occurred innermost try block points, followed by matching catch statement exception object (only type matching, catch parameters sometimes catch statement and will not be used to). If the match is successful, the implementation of exception handling catch block statements, and then execute the code block try ... catch ... later. If the current block within a try ... catch ... did not match the exception object catch statement by the more outer try ... catch ... block to handle the exception; if the current function of all the try ... catch ... block does not match the exception, then fall back on the recursive call stack layer to handle the exception. If you have been retreated to the main function main () can not handle the exception, the calling system function terminate () to terminate the program.
One of the most simple try ... catch ... an example is shown below. We have a program for students in the class record test scores, test scores scores range from 0 to 100, is not within the scope of this data is regarded as an exception:

int main ()
{
    int score = 0;
    while (cin >> score)
    {
        try
        {
            if (score> 100 || score <0)
            {
                throw score;
            }
            // Write the scores file or perform other operations
        }
        catch (int score)
        {
            cerr << "fractional value you entered is a problem, please re-enter!";
            continue;
        }
    }
}
back to the top
throw keyword

In the above example, throw a keyword and throw expression constitutes a throw statement. The syntax is:

throw expression;
throw statement must be included in the try block, you can also be included in the try block calls a function of the outer layer of the stack, such as:

// Sample code: throw in the try block contained in the outer function
void registerScore (int score)
{
    if (score> 100 || score <0)
        throw score; // throw statement is contained in the outer try block in main
    // Write the scores file or perform other operations
}
int main ()
{
    int score = 0;
    while (cin >> score)
    {
        try
        {
            registerScore (score);
        }
        catch (int score)
        {
            cerr << "fractional value you entered is a problem, please re-enter!";
            continue;
        }
    }
}
When the statement is executed throw, throw expression will be copied as objects constructed as a new object, called an exception object. The exception object placed in a special memory location, the location is neither the stack nor the heap, the window is placed in the thread information block TIB. The new object is constructed with the same level of catch corresponding try statement type matching, in principle match the type described below.

In this case, according to the object score constructed of type int, and the catch (int score) match, program control is transferred to the catch block statements, exception handling code for execution. If, within this function and type matching catch statement is unsuccessful, the call stack of the outer function continues to match, so recursively until the matching catch statement, or until no match on the main function and call the system function terminate () is terminated program.
When executing a throw statement throw statement following the statement will not be executed, syntax throw statement is somewhat similar to the return, thus resulting in the function call stack may be an early exit.

Exception object

The exception object is a special object, the compiler based copy constructor expression Thrown exception object, which requires the expression can not be thrown before an incomplete type (a type definition declared after an incomplete type Not full type means that the data type is not a complete description of the operation), and can be copy constructor, which requires an exception is thrown copy constructor expression (or mobile constructor), the destructor can not be private.

The exception object is different from the local object function, local objects are automatically destroyed after the end of the function call, and the exception object will reside in all of the catch statements may be activated to be able to access the memory space that is said above the TIB. When the exception object with the catch statement after a successful match, at the end of the catch statements are automatically destructed.

Returns the local variables in a function reference or pointer almost certainly caused the error, the same token, thrown pointer local variables in the throw statement or reference is almost wrong behavior. Unintended consequences if the pointer points to a variable has been destroyed in the implementation of catch statement pointer dereference will occur.

When throw out an expression, the expression of type static compiler will determine the type of the exception object. So when the solution is throw out a base class pointer references, and the actual object that the pointer points to a derived class object, then the derived class object cutting will occur.

In addition to user-defined type is thrown outside, C ++ standard library defines a set of classes, standard library functions users have reported problems encountered. The standard library exception class only defines several operations, including exception type create or copy the object, and the object type assignment exception.

Standard exception class header file description
The most common exception class exception, only reported exception occurred without providing any additional information exception
runtime_error only at run-time errors can be detected stdexcept
rang_error runtime error: generating meaningful beyond the range of values results stdexcept
overflow_error runtime error: Calculation overflow stdexcept
underflow_error runtime error: Calculation underflow stdexcept
logic_error program logic error stdexcept
domain_error logic error: the parameter values corresponding to the result of the absence of stdexcept
invalid_argument Logic Error: Invalid argument stdexcept
length_error logic error: trying to create a type of the object exceeds the maximum length stdexcept
out_of_range logic error: Using a value outside the valid range stdexcept
Dynamic memory allocation error bad_alloc new
bad_cast dynamic_cast type conversion error type_info
 
catch keywords

catch statement matches the exception object thrown. If the parameter catch statement is a reference type, this parameter can directly act on the exception object, namely to change the parameters of the exception object will change, and will continue to pass such a change in catch re-thrown. If the catch parameter is passed by value, the replication structure function will be based on the exception object to construct the catch parameter object. At the time of the catch end of the statement, the first parameter object destructor catch, then the exception object destructor.

During match exception object, the compiler will not do any type conversion or implicit type promotion. In addition to the following circumstances, the type of the exception object must declare the type of catch statement exact match:

Allows conversion from const type to the constant.
Allows a derived class to the base class type conversion.
The array is converted into a pointer to the array (element) type of pointer.
Function is converted to a pointer pointing to a function type.
Looking catch statement in the process, not necessarily the type of matches that exactly match the terms, but in the first catch statement that matches the most forward on (I call it the first matching principle). Therefore, the derived class handling code catch statement should be placed before the base class handle catch phrase, otherwise the first match is always on the parameter type is the base class catch statements, and can precisely match the catch statement can not be matched.

In the catch block, if you can not resolve the exception, we can continue to the outer thrown in the current function, so that the outer catch exception handling blocks are then processed. At this point you can use the throw statement with no expression captured exception re-thrown:

catch (type x)
{
    // Do some processing
    throw;
}
The exception object is thrown back in the TIB to preserve the exception object, there is no relationship with the catch of the parameter object if the catch parameter object is a reference type, you may have to modify the exception object in the catch statement, then re-throw the exception object is modified; if the catch parameter object non-reference type, then re-thrown exception object has not been modified.

Using catch (...) {} can catch all types of exceptions, according to the first matching principle, catch (...) {} should be placed in the rearmost catch all statements, otherwise it is impossible to make an exact match of the other can catch statement be matched. Typically execution of the current process can be done in a catch (...) {} statement, and then re-thrown. Note, catch re-thrown exception can only be captured outer catch statement.

back to the top
Stack unwinding, RAII

In fact, stack unwinding said earlier, that is, an exception is thrown from the point all the way to the outer function to find a matching catch statement process, looking for matches ending in a catch statement or standard library functions terminate. The focus here is to say stack unwinding process of the destruction of local variables. We know that at the end of the function call, local variables will be automatically destroyed, like, throw a block of statements may result in a call chain on early exit, this time, the statement block local variable will be generated in accordance with the constitution of the order reverse, turn calls the destructor destruction of the object. For example, the following example:

// No sense of a class
class A
{
public:
    A (): a (0) {cout << "A default constructor" << endl;}
    A (const A & rsh) {cout << "A copy constructor" << endl;}
    ~ A () {cout << "A destructor" << endl;}
private:
    int a;
};
int main ()
{
        try
        {
            A a;
            throw a;
        }
        catch (A a)
        {
            ;
        }
    return 0;
}

The definition of a variable called when the default constructor, call the copy constructor to initialize exception when using a variable, also called copy constructor when using the copy constructor catch exception variable parameter object. Three structure corresponding to the three destructor, namely the try block a local variables are automatically destructed. However, if a store is on the free allocated memory when:

int main ()
{
    try
    {
        A * a = new A;
        throw * a;
    }
    catch (A a)
    {
        ;
    }
    getchar ();
    return 0;
}

The same structure of three, but only two calls to the destructor! A description of the memory in the event of an exception has not been freed, a memory leak occurs.
RAII mechanism helps to solve this problem, RAII (Resource acquisition is initialization, resource acquisition is initialization). Its idea is to target resources management. For more convenient, robust release resources acquired, to avoid resource deadlock, one way is to use objects encapsulate data resources. Program exception occurs when the execution stack unwinding, encapsulates the target resource will be automatically call its destructor to free up resources. C ++ smart pointers will be eligible RAII. Details on this subject can be seen "Effective C ++" Article 13.

Exception mechanism constructor

A reasonable use exception mechanism is in the constructor. The constructor has no return value, so you should use the exception mechanism to report the problem. More importantly, the constructor throws an exception indicates that the constructor has not yet executed, the corresponding destructor will not be called automatically, so the destructor destructor should first of all all initialized base object, the member object, then an exception is thrown.
C ++ class constructor to initialize exception mechanism of the list, called function-try block. General form:

myClass :: myClass (type1 pa1)
    try: _myClass_val (initialization value)
{
  / * Function body constructor * /
}
  catch (exception & err)
{
  / * Exception handling section constructor * /
};
With the exception mechanism destructor

C ++ does not prohibit destructors throws an exception to the outside world, but the destructor is not thrown to the outside world expected function. Destructor outwardly throws an exception, the direct call terminator () system function terminates the program. If the inside of a destructor throws an exception, it should catch and handle the exception within the destructor, can not allow an exception to be thrown outside the destructor. It can be treated as such:

If the destructor throws an exception, call std :: abort () to terminate the program.
In the destructor catch catch the exception and processed.
About the details, interested can look "Effective C ++" clause 08: Do not let the abnormal escape destructor.

noexcept modifiers and noexcept operator

noexcept modifier is a new C ++ 11 provides an exception specifier used to declare a function does not throw an exception. The compiler can not be thrown for function optimization, another obvious benefit is that you define a certain function does not throw an exception, when someone calls your function will know without performing exception trap for this function. In C ++ 98 The procedures for exception handling you might see code like this:

void func () throw (int, double) {...}
void func () throw () {...}
This is a throw as a function exception specification, the former said func () function may throw exceptions of type int or double, which represents the func () function does not throw an exception. In fact the former is rarely used in C ++ 11 This practice has been abandoned, while the latter were C ++ 11 is replaced noexcept exception declarations:

void func () noexcept {...}
// Equivalent to void func () throw () {...}
In C ++ 11, the compiler does not compile in noexcept statement to check the function, therefore, it is declared as a function noexcept statement if an exception is thrown or carried by compilation. In the run-time function if an exception is thrown, the compiler can choose to directly call terminate () function to terminate the program run, therefore, a role noexcept is to prevent the spread of the exception, to improve security.

A little above mentioned, we can not allow an exception to escape the destructor, because that would lead to ambiguous behavior of the program or terminate the program directly. In fact, for security considerations, the destructor in C ++ 11 standard class to make the default is noexcept. Also for security reasons, is often delete destructor for releasing resources, C ++ 11 also set it to default noexcept.

noexcept can also accept a constant expression as an argument, for example:

void func () noexcept (constant expression);
The results of the constant expression will be converted to type bool, noexcept (bool) function does not represent an exception, noexcept (false) indicates that the function may throw an exception. So if you want to change the default destructor noexcept statement could be added explicitly noexcept (false) statement, but that does not give you any good.

Performance Analysis of exception handling

The main aspects of exception handling mechanism is the runtime type checking. When an exception is thrown, it must decide is not an exception thrown from the try block. Exception handling mechanism in order to improve matching between anomalies and its processor, each exception object type information, and additional information about the catch phrase needs to be stored. Because exception objects can be of any type (such as user-defined types), and may also be polymorphic, get its dynamic type must use run-time type checking (RTTI), also need to run the code of each function and information about Structure.

When an exception is thrown the point where the function does not resolve the exception, the exception object is passed out along the call chain, control of the program has also undergone a shift. The transfer process in order to carry the message of the exception object to the implementation of the program (such as the exception object copy constructor or destructor catch parameter) in time and space have to pay a certain price, itself unsafe, especially It is the exception object is a complex class time.

Exception handling technology implementations across different platforms and compilers are different, but the program will give additional burden when exception handling is turned off, the extra data structure, lookup tables, some additional code will not be generated, because of this, the clear not throw function, we need to use noexcept be declared.
     
         
       
         
  More:      
 
- How to view the Linux QPS (Linux)
- JavaScript function closures Quick Start (Programming)
- Smack 4.1.x Upgrade Guide (Linux)
- namespace mechanism Linux kernel analysis (Linux)
- Ubuntu Learning Advanced article - to teach you to further enhance system security (Linux)
- XtraBackup achieve non-stop use of master-slave synchronization service (Database)
- DVD production using CentOS installation source within the company Yum (Linux)
- Fedora network set up simple (Linux)
- OpenSUSE installation on CentOS6 (GUI) (Linux)
- Port Telnet command to detect the remote host is turned on (Linux)
- C ++ CBitmap, HBitmap, Bitmap difference and contact (Programming)
- Video editing captions under Linux (Linux)
- Ubuntu 14.04 LTS next upgrade gcc to gcc-4.9, gcc-5 version (Linux)
- Zombie process under Linux (Linux)
- How to install Gnome 3.10 in Ubuntu 13.10 (Linux)
- Present Situation and Development Trend of firewall products (Linux)
- Use Ansible efficient delivery Docker container (Server)
- Ubuntu development Nodejs (Linux)
- Linux pwd command learning experience (Linux)
- Upgrading to MySQL 5.7.9 MySQL 5.6.23 (Database)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.