Throwing exceptions and stack unwinding (stack unwinding)

Source: Internet
Author: User

When an exception is thrown, execution of the current function is paused, and the matching catch clause is started. First check whether the throw itself is inside the try block, and if so, check the catch clause associated with the try to see if the exception can be handled. If not, exit the current function, release the current function's memory and destroy the local object, and continue to the upper call function until you find a catch that can handle the exception. This process is referred to as stack unwinding (stack unwinding). When the catch that handles the exception finishes, the point immediately following the catch continues execution.

1. calling destructors for local objects

As mentioned above, in the process of stack unwinding, the memory occupied by the local object is freed and the destructor of the class type local object is run. However, it is important to note that if a block is dynamically allocated memory through new and an exception occurs before releasing the resource, the block exits with an exception, the resource is not freed during stack unwinding, and the compiler does not delete the pointer, which results in a memory leak.

2. destructors should never throw exceptions

When a stack is expanded for an exception, the destructor will cause the standard library terminate function to be called if it throws its own unhandled other exception. Normally the Terminate function calls the Abort function, which causes the program to exit abnormally. Therefore, the destructor should never throw an exception.

3. Exceptions and constructors

If an exception occurs while the constructor object is being constructed, the object may be partially constructed, ensuring that the constructed members are properly revoked.

4. uncaught Exception will terminate the program

You cannot handle exceptions. If no matching catch is found, the program calls the library function terminate.

Throwing exceptions and stack unwinding (stack unwinding)

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.