[Go] C + + Try Catch problem

Source: Internet
Author: User
Tags throw exception try catch

windhaunting, original address

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;     = (byte*)00001234 ;   // give an illegal address    6 // Assigning a value to an illegal address can cause an access violation exception     }    catch(...)    {    "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;     = (byte*)00001234 ;   // give an illegal address    6 // Assigning a value to an illegal address can cause an access violation exception     }    __except (exception_execute_handler)    {    "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.

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.

2. C + + catch (...) How to use
In the previous article, we described in detail the Trycatch usage syntax for the C + + exception handling model, 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 (...)".


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

intMain () {Try{cout<<"in the try block, prepare to throw an exception."<<Endl;//An exception is thrown here (where the data type of the exception object is int, and the value is 1)Throw 1;}//catch (int& value)//notice here that the Catch statementCatch(...) {cout<<"In the catch (...) block, the exception object that throws the int type is processed"<<Endl;}}

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

intMain () {Try{cout<<"in the try block, prepare to throw an exception."<<Endl;//An exception is thrown here (where the data type of the exception object is double and the value is 0.5)Throw 0.5;}//catch (double& value)//notice here that the Catch statementCatch(...) {cout<<"In the catch (...) block, an exception object of type Double 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:

intMain () {Try{cout<<"in the try block, prepare to throw an exception."<<Endl;//An exception is thrown here (where the data type of the exception object is char*)Char* p=0;Throwp;}//catch (char* value)//notice here that the Catch statementCatch(...) {cout<<"In the catch (...) block, the exception object of type char* is also handled"<<Endl;}}
//------------------------------------------------------------intMain () {Try{cout<<"in the try block, prepare to throw an exception."<<Endl;//An exception is thrown here (where the data type of the exception object is int[])inta[4];ThrowA;}//catch (int value[])//notice here that the Catch statementCatch(...) {cout<<"exception objects of type int[] are also handled in the catch (...) block"<<Endl;}}

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

classmyexception{ Public:protected:intcode;};intMain () {Try{cout<<"in the try block, prepare to throw an exception."<<Endl;//An exception is thrown here (where the data type of the exception object is myexception)Throwmyexception ();}//catch (myexception& value)//notice here that the Catch statementCatch(...) {cout<<"In the catch (...) block, the exception object of type MyException is processed"<<Endl;}}

To catch (...) A little confused?
1, exactly to catch (...) What's so confusing about it? Let's look at the example first!

voidMain () {int* p =0;Try{//Note: Although this statement is not a throw statement, it will cause the system to execute//An exception occurred with a storage protection error (Access violation exception)*p = -;//causes an access violation exception;}Catch(...) {//catch (...) Can you capture the above access violation exception exception? cout <<"In the 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:

voidFunc () {Try{//The program code here completes the really complex computational work that the code performs during the execution//It is possible to throw exception objects of type DataType1, DataType2, and DataType3. }Catch(datatype1&D1) {}Catch(datatype2&D2) {}Catch(datatype3&D3) {}//Note the DataType1, DataType2, and DataType3 that may be thrown in the try block above three//The exception object of the type is already in front of the corresponding catch block to handle. But why//also define a catch (...) at the end of the block? This is to have better security and//reliability, avoiding the process caused by the above try block throwing out other exception objects that are not considered//The serious consequences of unexpected crashes, and this is particularly effective on systems developed with VC,//for catch (...) Can catch the system anomalies, and the system anomaly often makes the programmer headache, now//in the system is generally more complex, and by a lot of people jointly developed, accidentally will lead to a//The pointer variable points to other illegal areas, resulting in an unexpected disaster. catch (...) For this//potential pitfalls provide an effective remedy. 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);returnFALSE;} 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 you does not need.#ifdef _afxdllenable3dcontrols ();//Call the When using the MFC in a shared DLL#elseenable3dcontrolsstatic ();//linking to MFC statically#endif//Note that there is a top-level trycatch block, and the catch (...) is used. To capture all the anomalies.Try{Cxxxdlg Dlg;m_pmainwnd= &Dlg;intNresponse =dlg. DoModal ();if(Nresponse = =IDOK) {//Todo:place code here-handle when the dialog is//dismissed with OK}Else if(Nresponse = =IDCANCEL) {//Todo:place code here-handle when the dialog is//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 .}//Since The dialog has been closed and return FALSE so that we exit the//application, rather than start the application ' s message pump.returnFALSE;}

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.

[Go] C + + Try Catch problem

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.