C + + exception handling catch (...) Introduction to _c language

Source: Internet
Author: User
Tags abstract exception handling prepare throw exception

What if you want to make a catch block capable of capturing unusual objects 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 dongdong, first to a perceptual knowledge bar!
See Example first:

Copy Code code as follows:

int main ()
{
Try
{
cout << "In the try block, prepare to throw an exception." << Endl;
This throws an exception (where the data type of the exception object is int and the value is 1)
Throw 1;
}
catch (int& value)
Notice here the Catch statement
catch (...)
{
cout << "in catch (...) block, the exception object thrown by the int type is handled "<< Endl;"
}
}

2, haha!int type of exception is catch (...) Captured, and then another example:
Copy Code code as follows:

int main ()
{
Try
{
cout << "In the try block, prepare to throw an exception." << Endl;
This throws an exception (where the data type of the exception object is double, and the value is 0.5)
Throw 0.5;
}
catch (double& value)
Notice here the Catch statement
catch (...)
{
cout << "in catch (...) In block, the exception object of double type is also processed "<< Endl;"
}
}

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

int main ()
{
Try
{
cout << "In the try block, prepare to throw an exception." << Endl;
This throws an exception (where the data type of the exception object is char*)
char* p =;
throw p;
}
catch (char* value)
Notice here the Catch statement
catch (...)
{
cout << "in catch (...) block, the char* type of exception object is also processed "<< Endl;"
}
}
int main ()
{
Try
{
cout << "In the try block, prepare to throw an exception." << Endl;
This throws an exception (where the data type of the exception object is int[])
int a[4];
throw A;
}
catch (int value[])
Notice here the Catch statement
catch (...)
{
cout << "in catch (...) block, the exception object of the int[] type is also handled "<< Endl;"
}
}

4. An exception object for an abstract data type. catch (...) Equally valid, the routines are as follows:
Copy Code code as follows:

Class MyException
{
Public
Protected
int code;
};
int main ()
{
Try
{
cout << "In the try block, prepare to throw an exception." << Endl;
This throws an exception (where the data type of the exception object is myexception)
throw MyException ();
}
catch (myexception& value)
Notice here the Catch statement
catch (...)
{
cout << "in catch (...) block, the MyException type of exception object is processed "<< Endl;"
}
}

For catch (...) A little confused?
1, on the catch (...) What's so confusing about it?Let's look at the example first!
Copy Code code as follows:

void Main ()
{
int* p = 0;
Try
{
NOTE: The following statement, although not a throw statement, will cause the system to execute
An exception with a storage protection error occurred (access violation exception)
*p = 13; Causes an access violation exception;
}
catch (...)
{
catch (...) Can you capture the above access violation exception exception?
cout << "in catch (...) Block in "<< Endl;
}
}

Can you tell me what happens when the above program runs? catch (...) Can you capture the access violation exception exception that appears in the system? Friends! And our hero Ahan, like, to test their own hands!

What about the results? In fact, it has two different operating results, in the window2000 system with VC to test the running of this applet, the Discovery program can output "in the catch (...) block" statement on the screen, also known as catch (...) Can successfully capture the system appears in the access violation exception abnormal, very powerful bar! But if the same program is compiled with GCC under Linux, the program crashes and prints "segment fault" error messages on the screen.

The protagonist Ahan a little anxious, also began a bit confused, why? Why not? Why is the same program performing differently on two different systems? The reason for this is this: for this system exception due to hardware or operating system (for example, 0 exception, memory storage Control exceptions, page faults, and so on), The window2000 system has a mechanism called structured exception handling (structured Exception Handling,seh), which is so powerful that it can be combined with VC's C + + exception handling model (in fact VC implementation of C + + The exception-handling model is largely based on the SEH mechanism, or it is an extension of SEH, and later articles will elaborate and analyze this long renowned seh to see the catch (...). is how to magically take over the program flow after this system anomaly occurs, but this is something. In Linux system, System anomaly is controlled by signal processing programming (signal processing programming, signal processing progamming). In books that describe how UNIX and Linux are programmed, will have a detailed introduction of signal processing programming, of course, the protagonist Ahan will certainly not let go, in-depth to the UNIX signal Processing programming internal implementation mechanism, and try to improve it, so that it can also better and C + + The exception handling model is combined).

So what does the C + + standard have to say about the different running results of this same program? It should be noted that the window2000 system is under catch (...) Can capture the system exception, which is entirely its own extension. This is not required in the C + + standard, it only stipulates catch (...) You must be able to capture all exceptions thrown by throw statements in your program. Therefore, the above program in the Linux system operating results are entirely in line with the C + + standard. Although we must admit that this extension 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?
Programmer friends might say, is this still a question? The beginning of this article is not the first? catch (...) Can capture the exception object of a variety of data types, so it provides programmers with a better control of the exception object, so that the development of the software system has good reliability. So a more experienced programmer would normally organize the code modules for it, as follows:

Copy Code code as follows:

void Func ()
{
Try
{
The program code here completes the really complex computations that, during execution,
It is possible to throw exception objects of the DataType1, DataType2, and DataType3 types.
}
catch (datatype1& D1)
{
}
catch (datatype2& D2)
{
}
catch (datatype3& D3)
{
}
Note The DataType1, DataType2, and DataType3 three that may be thrown in the try block above
A type of exception object already has a corresponding catch block in front of it. But why
Do you want to define a catch (...) block at the end? That's for better security and
Reliability to avoid the process that occurs when the above try block throws out other exception objects that are not considered
Sequence has the serious consequences of an accidental crash, and this is more particularly effective in systems developed with VC
For catch (...) Can capture the system of the exception, and system abnormalities often make programmers headache, now
In the system is generally more complex, and by a lot of people jointly developed, inadvertently 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 make the development of the system has better reliability, often in the application of the portal function (such as the MFC framework in the Development environment Cxxxapp::initinstance ()) and the work of the entry function of the worker thread add a top-level trycatch block, and use catch (...) To catch all the exceptions, as follows:
Copy Code code as follows:

BOOL cxxxapp::initinstance ()
{
if (! AfxSocketInit ())
{
AfxMessageBox (idp_sockets_init_failed);
return FALSE;
}
AfxEnableControlContainer ();
Standard initialization
If you are are not using this features and wish to reduce the size
of your final executable, your should remove from the following
The specific initialization routines you don't need.
#ifdef _afxdll
Enable3dcontrols (); Call the When using MFC in a shared DLL
#else
Enable3dcontrolsstatic (); Linking to MFC statically
#endif
Note that there is a trycatch block at the top level and use catch (...) To catch all the anomalies
Try
{
Cxxxdlg Dlg;
m_pMainWnd = &dlg;
int nresponse = dlg. DoModal ();
if (Nresponse = = Idok)
{
Todo:place code here to handle when the dialog is
Dismissed with OK
}
else if (nresponse = = IDCANCEL)
{
Todo:place code here to handle when the dialog is
Dismissed with Cancel
}
}
catch (...)
{
Dump some important information about the system and notify the Administrator of the reason for the unexpected exception.
Try to recover the system at the same time, such as restarting the application.
}
Since the dialog has 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 (...) The 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. It is true that everyone uses catch (...) The best reason for this stuff. But don't get me wrong, in the C + + exception handling model, there is not only catch (...) Method can capture almost any type of exception object.

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.