Exception handling in c++

1. Definition

    If an exception is found in the process of executing a function, you can throw the exception instead of processing it immediately in this function, and let the function

    The caller handles this directly or indirectly.

    The exception handling mechanism in c++ consists of three modules: try (check), throw (throw), catch (capture)

2. Use

    Matching rules for exception capture:

    The type of exception thrown in the try block is the type of exception that is caught in the catch. In general, the type must match exactly, but

    Type conversion can be performed in the following 3 cases:

    1. Allow conversion from non-const objects to const

        That is, throw a non-const object, catch a const object

    2. Allows conversion from derived class types to base class types

        That is, throw a derived class object and catch a base class object

    3. Convert an array to a pointer to an array type, and a function to a pointer to a function type

    Example:

void divide(int x,int y)//Exception thrown
{
	if (y == 0)
	{
		throw x;
	}
	cout<<(x/y)<<endl;
}
void Mydivide(int x,int y)
{
	try
	{
		divide(x,y);	
	}
	catch(int e)
	{
		cout<<e<<"除以0"<<endl;
	}
	catch(...)//After receiving the exception, you can not handle it and throw it directly
	{
		cout<<"other unknown type exception"<<endl;
		throw ;
	}
}
intmain()   
{
	Mydivide(10,0);
	Mydivide(100,10);
}
 

    

Welcome to point out the shortcomings

    

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326641986&siteId=291194637