Exceptions

Hello,

I need help with an assignment that asks for me to throw an exception if a value is out of bounds. I am a beginner at exceptions and do not understand what I need to do here to make this work.

My code is listed below. Main calls the retrieve function. I have a lot of processing in main and basically need for main to continue to execute when this exception is thrown. Hoping someone can lead me in the direction I need to go to solve this. Currently, when the condition is true and index is out of bounds, I get a popup with error (see below) and my program stops processing. Thanks!

"Debug Error: This application has requested that Runtime terminate in an unusual way....Press retry to debug the application...Abort, Retry, Cancel".

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
template< typename NODETYPE >
NODETYPE List< NODETYPE >::retrieve( int index )
{ 
	if(index < 0 || index > 100)
	{
		throw invalid_argument("index not valid");

	}

        //set pointer to the first node
	ListNode< NODETYPE > *currentPtr = front;
 
	for(int i=0; i < index; i++)
	{
		currentPtr = currentPtr->nextPtr;
	}

	return currentPtr->data;
} 


......The function call from Main ()
1
2
3
4
   List < string > test;
   cout << "Get the value in index 1000 of the linked list:  ";
   cout << test.retrieve(1000) << "\n\n\n";
You need to catch the exception, i.e. enclose the call in a try/catch block.
Thanks, I will work on placing a try/catch around the function call in main(). Are there any special #include statements that I need to use to throw these exceptions? I saw conflicting statements about including <stdexcept>. Thanks!
I got it to work by placing a try catch around my statment in main. I did not need an extra include statement to make it work.


<code>
List < string > test;
cout << "Get the value in index 1000 of the linked list: ";

try
{
cout << test.retrieve(1000) << "\n\n\n";
}
catch (exception& e)
{
cout << e.what() << "\n\n";
}

</code>
Topic archived. No new replies allowed.