I need some help understanding how the exception handling flow of code works. I have written a sample program that has exception handling in it. There are two classes here: My custom Array class and the Main.cpp class to implement and test the Array class.

Inside the main() method, I have a for loop that updates the value of each element in the array by calling this method inside my custom array class

//Setter Data
void TestInt::setData( int const index, int const d )
{
	//Check for Index bounds....
	cout << "Method: setData() triggered...." << endl;
	if ( (index < 0) || (index >= size) )
	{
		throw exception("\nEXCEPTION: setData() triggered....");
	}
	else { data[index] = d; }
}

I start the for-loop with my counter starting at -1, by design so an exception is thrown. But once the exception has been handled, continued after code snippet

#
for ( int i= -1; i< test->Capacity(); ++i )

How do I get back to the for-loop so it continues running the program with counter incrementing to one(1)....

Please advise

Here is the entire main() method code I need help with:

//DECLARE: Custom Exception class

#include "TestInt.h"

#include <iostream>
#include <string>
#include <stdexcept>
#include <exception>
using namespace std;

void Test_ArrayClass();

int main()
{
	Test_ArrayClass(); // method body below...
	system("PAUSE"); return 0;
};

void Test_ArrayClass()
{
	TestInt *test = new TestInt(5);
	test->Display();

	int count = 0;
	cout << "\n\n" << endl;

	//Fill Array & test Exception.....
	try
	{
		/*
		***********************************************************************
		* Testing Exception Handling: For-Loop
		* After exception is recognized it is thrown to the catch-block
		* but how do I get back to the for-loop......any suggestions/ideas???
		***********************************************************************
		*/
		for ( int i= -1; i< test->Capacity(); ++i )
		{
			test->setData(i, ++count);
		}
		cout << "\nafter for-loop.....\n" << endl;
		test->Display();
	}
	catch(exception &e) //catch (out_of_range &e)
	{
		cout << "\ntest inside catch block\n" << endl;
		cout << e.what() << "\n\n" << endl;
		delete test;  test = NULL;
		//return;
	}
	cout << "\nafter the catch block.....\n" << endl;

	test->Display();
	delete test;  test = NULL;
}

Recommended Answers

All 2 Replies

Put the try-catch inside the for loop.

Put the try-catch inside the for loop.

Thank you Andrew Koenig for your help.
I have spend almost 3 weeks now, trying different things to my sample code, as well as read exceptional handling chapters in about 15 C++ books.
Should have posted earlier but the joy of finding solutions to problems seemed better earlier.

commented: disagree ! C++ industry professionals are encouraged to use exceptions. +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.