C + + Try Catch problem (no throw will be removed, plus/eha will not be deleted)

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:

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:

    1. Try
    2. {
    3. byte* PCH;
    4. PCH = (byte*) 00001234; Give an illegal address
    5. *PCH = 6; Assigning a value to an illegal address can cause an access violation exception
    6. }
    7. catch (...)
    8. {
    9. AfxMessageBox ("catched");
    10. }

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.

    1. __try
    2. {
    3. byte* PCH;
    4. PCH = (byte*) 00001234; Give an illegal address
    5. *PCH = 6; Assigning a value to an illegal address can cause an access violation exception
    6. }
    7. __except (Exception_execute_handler)
    8. {
    9. AfxMessageBox ("catched");
    10. }

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.

Find a better English article to talk about this question: http://members.cox.net/doug_web/eh.htm

With c++10 years more, incredibly so basic problems are mistaken, really ashamed. To step up learning ah, stay hungry, stay foolish!

Written by Oldmonk on September 11th, 2006 with 2 comments. Read more articles on IT.

Http://se.csai.cn/ExpertEyes/No138.htm C + + in catch (...) How to use the Trycatch syntax for the C + + exception handling model in the previous article, where the catch keyword is used to define a catch block, followed by a parameter that matches the data type of the exception object. Note The Catch keyword can only define one parameter, so each catch block can only be an error-handling module for the exception object of a data type. What if you want a catch block to capture an exception object of multiple data types? A special catch usage is defined in the C + + standard, which is "catch (...)".

Perceptual
1. catch (...) In the end is a what kind of east, first to a perceptual knowledge it! See Example first:

int main () {try {cout << "in try block, prepare to throw an exception." << Endl;//Throws an exception here (where the data type of the exception object is int, the value is 1) throw 1;}//ca TCH (int& value)//note here Catch statement catch (...) {cout << "in catch (...) block, the exception object thrown by the int type is handled "<< Endl; } }

2, haha! An exception of type int is caught (...) Captured, and then another example:

int main () {try {cout << "in try block, prepare to throw an exception." << Endl;//Throws an exception here (where the data type of the exception object is double and the value is 0.5) throw 0.5; }//catch (double& value)//note here Catch statement catch (...) {cout << "in catch (...) In block, a double type of exception object is also handled "<< Endl; } }

3. Similarly, an exception object of type Double is also caught (...). Block was captured. Yes, catch (..) Exception objects that match all successful data types, including the C + + language, which provides all of the native data types of exception objects, such as int, double, pointer types such as char*, int*, and exception objects of the array type. It also includes all of the custom abstract data types. The routines are as follows:

int main () {try {cout << "in try block, prepare to throw an exception." << Endl;//Throws an exception here (where the data type of the exception object is char*) char* p=0; P }//catch (char* value)//note here Catch statement catch (...) {cout << "in catch (...) block, char* type of exception object is also handled "<< Endl; } }

int main () {try {cout << "in try block, prepare to throw an exception." << Endl;//Throws an exception (where the data type of the exception object is int[]) int a[4]; throw a ; }//catch (int value[])//note here Catch statement catch (...) {cout << "in catch (...) block, int[] Type of exception object is also handled "<< Endl; } }

4. Exception object for abstract data type. catch (...) Equally valid, the routines are as follows:

Class MyException {public:protected:int code;};

int main () {try {cout << "in try block, prepare to throw an exception." << Endl;//Throw an exception here (where the data type of the exception object is myexception) throw Myexc Eption (); }//catch (myexception& value)//note here Catch statement catch (...) {cout << "in catch (...) block, MyException type of exception object is handled "<< Endl; }} to catch (...) A little confused? 1, exactly to catch (...) What's so confusing about it? Let's look at the example first! void Main () {int* p = 0;

try {//NOTE: The following statement, although not a throw statement, will cause the system to execute with a storage protection Error exception (access violation exception) *p =;//causes an Access Violat Ion exception; } catch (...) {//catch (...) Can you capture the above access violation exception exception? cout << "in catch (...) Block "<< Endl; } }

What happens when the above program is running? catch (...) Can you catch the access violation exception exception that appears in your system? My friends! Just like our hero Ahan, do your own testing! And what about the results? In fact, it has two different operating results, in the window2000 system with the VC to test running the applet, the Discovery program can output "in the catch (...) block" statement on the screen, also known as the catch (...) can successfully capture the presence of access in the system Violation exception abnormal, very bad! But if the same program runs under Linux with GCC, the program crashes and prints "segment fault" error messages on the screen.
The protagonist Ahan a little hurry, also began a bit confused, why? Why? Why does the same program have different performance on two different systems? The reason for this is that the window2000 system has a system called structured exception handling (structured Exception handling, for example, in addition to 0, memory-storage Control exceptions, page faults, etc.) due to the hardware or OS anomalies. SEH) mechanism, this thing is too powerful, it can and VC C + + exception processing model is very good combination (in fact, VC implementation of C + + exception processing model is largely based on the SEH mechanism, or it is an extension of SEH, the later article will elaborate and analyze this long-known seh, See catch (...) is how to magically take over the program flow of this system exception, but this is something). In the Linux system, the system anomaly is controlled by the signal processing programming method (signal processing programming, signal processing progamming. In the introduction of UNIX and Linux how to program the book, there will be a detailed introduction of signal processing programming, of course, the hero Ahan certainly will not let go, will be deep into the Unix lineage down the signal processing programming internal implementation mechanism, and try to improve it, so it can also better and C + + Exception handling model combined).
So what does the C + + standard say about the different running results of this same program? It is important to note that the window2000 system catch (...) Can capture system anomalies, which is entirely its own extension. This is not required in the C + + standard, it only specifies the catch (...) You must be able to catch all exceptions thrown through the throw statement in the program. Therefore, the above program in the Linux system running results are fully compliant with the C + + standard. While it is important to acknowledge that this expansion of the C + + exception handling model under the window2000 system is indeed a very good improvement, greatly improving the security of the program.

Why use catch (...) This stuff?
The programmers ' friends might say, is there any question? Did you get to the beginning of this article? catch (...) Can capture a variety of data types of exception objects, so it provides programmers a better control of the exception object, so that the development of software systems have a good reliability. So a more experienced programmer would normally organize the code modules to write it, as follows:

void Func () {try {//) The program code here completes a truly complex calculation that, during execution, may throw DataType1, DataType2, and DataType3 types of exception objects. } catch (datatype1& D1) {} catch (datatype2& D2) {} catch (datatype3& d3) {}//Note the DataType1, D, which may be thrown in the try block above AtaType2 and DataType3 three//type of exception object is already in front of the corresponding catch block to handle. But why//Are you going to define a catch (...) block at the end? This is in order to have better security and/or reliability, to avoid the above try block throws other not considered exception object caused by unexpected crash of the process//sequence, and this in the VC developed by the system more particularly effective, because//for catch (...) Can catch system anomalies, and system anomalies tend to make programmers headache, now//In the system is generally more complex, and by a lot of people jointly developed, accidentally will lead to a//pointer variable pointing to other illegal areas, resulting in an unexpected disaster happened. catch (...) Provides an effective remedy for this//potential pitfalls. catch (...) { } }
Also, in particular, VC programmers in order to develop a system with better reliability, often in the application of the entry function (such as the MFC framework of the Development environment Cxxxapp::initinstance ()) and the entry function of the worker thread to add a top-level trycatch block, and use catch (...) To catch all the exceptions, as follows:

BOOL cxxxapp::initinstance () {if (! AfxSocketInit ()) {AfxMessageBox (idp_sockets_init_failed); return FALSE;}

AfxEnableControlContainer ();

Standard initialization//If You is not using these features and wish to reduce the size//of your final executable, You should remove from the following//the specific initialization routines your do not need.

#ifdef _afxdll enable3dcontrols (); Call the When using the MFC in a shared DLL #else enable3dcontrolsstatic (); Linking to MFC statically #endif

Note that there is a top-level trycatch block, and the catch (...) is used. To catch all the exceptions try {Cxxxdlg dlg; m_pmainwnd = &dlg; int nresponse = dlg. DoModal (); if (Nresponse = = IDOK) {//Todo:place code here to handle when the dialog are//dismissed with OK} else if (Nresponse = = IDCANCEL) {//Todo:place code here to handle when the dialog are//dismissed with Cancel}} catch (...) {//Dump some important information from the system and notify the administrator to find out why the unexpected exception occurred. Try to recover the system at the same time, such as restarting the application, etc.}

Since the dialog have been closed, return FALSE so, we exit the//application, rather than start the application ' s Message pump. return FALSE; }

Through the above routines and analysis can be drawn, due to catch (...) Ability to capture exception objects of all data types, so use catch (...) in the right place It is true that software systems can be more reliable. This is really everyone using catch (...) The best reason for this stuff. But don't be mistaken, in the C + + exception handling model, there is not only catch (...) Method can capture almost all types of exception objects (perhaps there are other better ways, the protagonist Ahan in the next article to discuss), why would the C + + standard Think of defining such a catch (...)? Programmers who have had Java or C # programming experience will find that in their exception handling model, there is no such a syntax, but again, the exception handling model in Java is a perfect and improved version of the exception handling model in C + +, but instead of a catch (...), Why is it? Let's take a look at the next chapter, "Exception handling for C + + and object-oriented intimacy". Maybe we can find a reason that seems reasonable.

Http://www.cnblogs.com/MaxWoods/p/4050828.html

C + + Try Catch problem (no throw will be removed, plus/eha will not be deleted)

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.