VC + + Try catch (go)

Source: Internet
Author: User
Tags try catch

Used to be try{} catch (...) {} to catch some unexpected exceptions in C + +, today read Winhack's post only to know, this method in VC is actually unreliable. For example, the following code:
Try
{
byte* PCH;
PCH = (byte*) 00001234; Give an illegal address

*PCH = 6; Assigning a value to an illegal address can cause an access violation exception
}
catch (...)
{
AfxMessageBox ("catched");
}

This code is not a problem in debug, the exception will be caught, will pop up "catched" message box. However, if the compiler Code optimization option is selected in Release mode, the VC compiler will search the code in the try block, and if the throw code is not found, he will assume that the try catch structure is redundant and is optimized. This causes the exception in the above code to be caught in release mode, forcing the program to pop out of the error notification box.
So can you catch this exception in the Release code optimization State, the answer is yes. is __try, __except structure, the above code if changed to the following code exception can be captured.
__try
{
byte* PCH;
PCH = (byte*) 00001234; Give an illegal address

*PCH = 6; Assigning a value to an illegal address can cause an access violation exception
}
__except (Exception_execute_handler)
{
AfxMessageBox ("catched");
}

But with __try, the __except block still has a problem, which is not the C + + standard, but the Windows platform-specific extensions. And if a call to a local object destructor is involved in the process, a C2712 compilation error occurs. So there's no other way?
Of course, it is the try{}catch that still uses the C + + standard (..) {}, but add the/EHa parameter to the compile command line. This way the VC compiler does not optimize the try Catch module.

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.