Example of C + + exception handling mechanism and detailed explanation of _c language

Source: Internet
Author: User
Tags define function error code exception handling function prototype

These two days I wrote a test of C + + exception handling mechanism of an example, feel a good demonstration of the role, posted here, to the C + + exception handling beginners to get started. This article is accompanied by C + + abnormal knowledge popularization, interested people can also see.

The following code is attached directly to your console project, you can run debugging to see the effect, and analyze the exception mechanism of C + +.

Copy Code code as follows:

#include "stdafx.h"
#include <stdlib.h>
#include <crtdbg.h>
#include <iostream>
Memory leak detection mechanism
#define _crtdbg_map_alloc
#ifdef _DEBUG
#define NEW New (_normal_block, __file__, __line__)
#endif

Custom exception Classes
Class Myexcepction
{
Public

constructor, parameter is error code
myexcepction (int errorid)
{
Output constructor called information
Std::cout << "Myexcepction is called" << Std::endl;
M_errorid = ErrorID;
}

Copy Constructors
Myexcepction (myexcepction& myexp)
{
Output copy constructor called information
Std::cout << "Copy construct is called" << Std::endl;
This->m_errorid = Myexp.m_errorid;
}

~myexcepction ()
{
Output destructor called information
Std::cout << "~myexcepction is called" << Std::endl;
}

Get error code
int Geterrorid ()
{
return M_errorid;
}

Private
Error code
int M_errorid;
};

int main (int argc, char* argv[])
{
Memory leak detection mechanism
_CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _crtdbg_leak_check_df);

You can change the error code to throw different exceptions for testing
int throwerrorcode = 110;

Std::cout << "input test code:" << Std::endl;
Std::cin >> Throwerrorcode;

Try
{
if (Throwerrorcode = 110)
{
Myexcepction Mystru (110);

The address-> of the thrown object is captured by catch (myexcepction* pmyexcepction)
Here the address of the object is thrown to the catch statement, and the copy constructor of the object is not invoked
An address is an advocated practice that does not frequently call the object's constructor or copy constructor
After the execution of the catch statement, the Mystru will be destructor
Throw &myStru;
}
else if (Throwerrorcode = 119)
{
Myexcepction Mystru (119);

//  throws objects, where a temporary object is created by the copy constructor outbound to catch
//  by catch ( myexcepction myexcepction)   capture
//  will call again in the Catch statement to create a temporary object copy from the copy constructor
// throw after the end of the Mystru will be destructor
throw mystru; 
}
else if  ( throwErrorCode == 120 )
{
//  does not promote such a throw method
//   If you do this, a memory leak occurs if you do not perform a delete operation in catch ( myexcepction* pmyexcepction)

Caught by catch (myexcepction* pmyexcepction)
Myexcepction * Pmystru = new Myexcepction (120);
Throw Pmystru;
}
Else
{
Creating a new object directly throws
is equivalent to creating a temporary object passed to a catch statement
Create a temporary object again through a copy constructor when received by catch pass objects in the past
Temporary objects created two times after the end of throw will be destructor
Throw myexcepction (Throwerrorcode);
}
}
catch (myexcepction* pmyexcepction)
{
Output This statement is executed information
Std::cout << "Executed catch (myexcepction* pmyexcepction)" << Std::endl;

Output error message
Std::cout << "error Code:" << pmyexcepction->geterrorid () << Std::endl;

The new object thrown by the exception is not created on the function stack, but is created on a dedicated exception stack and does not require a delete
Delete pmyexcepction;
}
catch (Myexcepction myexcepction)
{
Output This statement is executed information
Std::cout << "Executed catch (myexcepction myexcepction)" << Std::endl;

Output error message
Std::cout << "error Code:" << myexcepction.geterrorid () << Std::endl;
}
catch (...)
{
Output This statement is executed information
Std::cout << "Execute catch (...)" << Std::endl;

Can't handle it, throw it back to the superior
throw;
}

Time out
int temp;
Std::cin >> temp;

return 0;
}


Knowledge Point: C + + exception mechanism

I. Overview

C + + itself has a very strong ability to error correction, developed to now, has established a relatively perfect exception handling mechanism. C + + Abnormal situation is nothing more than two, one is a grammatical error, that is, the program appears in the wrong statements, functions, structures and classes, resulting in the compiler can not be carried out. The other is a run-time error, generally related to the algorithm.

About syntax error, needless to say, write code forestall a point can be solved. The C + + compiler's error mechanism allows us to easily resolve these errors.

The second is Run-time errors, common file open failure, array subscript overflow, system memory shortage, and so on. However, once these problems occur, the failure of the algorithm, the failure of the program to stop for no reason, is often the case. This requires us to design software algorithms in a comprehensive way. For example, for file open failure, there are many ways to protect, the simplest is to use the "return" command to tell the upper-level caller function execution failed; Another approach is to use the exception mechanism of C + + to throw exceptions.

Second, C + + exception handling mechanism

The C + + exception handling mechanism is a very powerful and flexible tool to effectively handle running errors, providing more flexibility, security, and robustness, overcoming the problems of traditional methods.

The throwing and handling of exceptions mainly uses the following three keywords: try, throw, catch.

Throwing an exception detects whether an exception is generated, in C + +, it is implemented using a throw statement, and if an exception is detected, an exception is thrown. The format of the statement is:
Expression of throw;
If an exception is found in the program segment of the TRY statement block, including the function called in it, and discarding the exception, the exception can be caught and handled by a catch statement after the try statement block, and the condition that the thrown exception is the type that matches the exception type of the catch statement. Because C + + uses data types to differentiate between exceptions, the value of an expression in a throw statement is not meaningful when judging an exception, and the type of the expression is particularly important.

The Try-catch statement forms the following:

Copy Code code as follows:

Try
{
Contains statements that may throw exceptions;
}

catch (type name [formal parameter name])//Catch a specific type of exception
{
}
catch (type name [formal parameter name])//Catch a specific type of exception
{
}
catch (...)//three points indicates that all types of exceptions are caught
{
}


"Example 1" handles an exception with a divisor of 0. This example uses the Try/catch statement to catch an exception with a 0 exception, and use the throw statement to throw an exception, which enables exception handling, as shown in listing 1-1 of code.
Code Listing 1-1
Copy Code code as follows:

#include <iostream.h>//Include header file

#include <stdlib.h>

Double fuc (double x, double y)//define function
{
if (y==0)
{
Throw y; Divisor is 0 and throws an exception
}
return x/y; Otherwise return two number of quotient
}
void Main ()
{
Double res;
Try//Definition exception
{
RES=FUC (2,3);
cout<< "The result of x/y is:" <<res<<endl;
RES=FUC (4,0); An exception appears, and an exception is thrown inside the function
}
catch (double)//catch and handle exceptions
{
cerr<< "error of dividing zero.\n";
Exit (1); Exception Exit Program
}
}


"Example 2" Custom exception type (demonstrated in the code at the beginning of this article)

Third, the interface declaration of the exception

To enhance the readability of the program so that users of the function can easily know what exceptions are thrown by the function they are using, you can list all the exception types that the function might throw in the declaration of the function, for example:

void Fun () throw (a,b,c,d);

This indicates that the function fun () May and only throw the exception of the type (A,B,C,D) and its subtypes.

If an interface declaration for an exception is not included in the declaration of a function, this function can throw any type of exception, for example: void Fun ();

A function that does not throw out any type of exception can declare the following form:

void Fun () thow ();

Problems needing attention in exception handling

1. If the thrown exception has not been a function capture (catch), it will be uploaded to the C + + running system, resulting in the termination of the entire program

2. Normally the resource can be released normally after the exception is thrown, but note that if an exception is thrown in the constructor of the class, the system will not call its destructor, and the processing method is: If you want to throw an exception in the constructor, remember to delete the requested resource before throwing it.

3. Exception handling is matched only by type rather than by value, so the parameters of the catch block can have no parameter name, only the parameter type.

4. The description of the exception in the function prototype is consistent with the exception description in the implementation, otherwise it can easily cause an exception conflict.

5. When the exception object is written after the throw statement, throw constructs a new object through the copy constructor and passes the new object to the catch.

So how does the new object release when the exception is thrown?
The exception handling mechanism guarantees that the new object thrown by the exception is not created on the function stack, but is created on a dedicated exception stack, so that it can be passed across multiple functions to the upper level, otherwise it will be destroyed during stack emptying. The destructor of all objects constructed from try to throw statements is automatically invoked. However, if a matching catch block has not been found since the main function has been traced, the system call terminate () terminates the entire program, which does not guarantee that all local objects will be destroyed correctly.

6. The parameters of the catch block recommend address delivery rather than value transfer, not only to improve efficiency, but also to take advantage of object polymorphism. In addition, the exception flutter of the derived class is to be placed in front of the parent class exception, otherwise the exception of the derived class cannot be caught.

7. When writing an exception description, ensure that the exception description of the derived class member function is consistent with that of the base class member function, that is, the exception description of the virtual function overridden by the derived class should be at least the same as the exception description of the corresponding base class virtual function, even stricter and more special

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.