[Solved] C++ Error: terminate called after throwing an instance of ‘char const‘

0. Error Codes:

//insert
template <class DataType>  
void SeqList<DataType> :: Insert(int i, DataType x)
{
	if (i >= MaxSize)  throw "up";
	if (i < 1 || i > length + 1)  throw "The postions is not right";
	for (int j = length; j >= i; j--)
		data[j] = data[j - 1];             //Note that the jth element exists at the j-1 subscript of the array
	data[i - 1] = x;
	length++;
}


//main function
int main(){
	int r[5]={1, 2, 3, 4, 5};
	SeqList<int> L(r, 5);
	cout<<"The data after performing the insert operation is:"<<endl;
	L.PrintList( );              //output all elements
	try{
//		L.Insert(2,10);
		L.Insert(10,30);
	}catch(char *e){
		cout<<e<<endl; 
	}
	cout<<"The data after performing the insert operation is:"<<endl;
	L.PrintList( );              //output all elements

In fact, the code is still relatively easy, it is an insertion problem in an array, in an inserted array in the wrong position, it will report an exception to handle. But in this program the exception is not caught, but the program will stop for a long time in the middle and show terminate called after throwing an instance of ‘char const*’, the reason for this situation is that the exception does not match up in the catch, the C++ destructor throws The exception will automatically call terminate() to terminate the program. Then how to solve this situation?

1. Problem-solving
In fact, it is very simple to solve the problem, just add const in front of char *e in catch, here char *e is turned into a string constant pointer.

int main(){
	int r[5]={1, 2, 3, 4, 5};
	SeqList<int> L(r, 5);
	cout<<"The data before performing the insert operation is:"<<endl;
	L.PrintList( ); //output all elements
	try{
// L.Insert(2,10);
// The reason for the problem is that the exception type does not match and c++ starts its own exception handling
// Solution: just add const in front of char to make the caught exception variable a constant 
		L.Insert(10,30); // the second parameter 30 will cause an exception to be thrown (i > length + 1)  
	}catch(const char *e){
		cout<<e<<endl; 
	}
	cout<<"After performing the insert operation the data is:"<<endl;
	L.PrintList( ); //output all elements

}

 

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *