Issues with exceptions

So I"m having some issues with exceptions. I don't even know if I'm doing it right or not. All I want is to have a user select an equation and if the number is out of range to catch and throw back an error message.

So In my main function I have the following:

1
2
3
4
5
6
7
8
9
10
11
...
case 1:
{
	std::cout << "\nWhich equation would you like to print: ";
	std::cin  >> whichOne;
								
	e.printEquation(std::cout, whichOne);
                        		
	break;
}
...



in my class I have the following:

1
2
3
4
5
6
...
	if(which > MAX_EQUATIONS || which < 0) throw OutOfRange("\nNumber is out of range.\n");
    	
	os << "Equation "<< which << " is: ";
	equations[which-1].print(std::cout);
...



I don't think I have to post the OutOfRange.h so I'll just leave it at that.

The code compiles with no problems... If I pick a number within the ranger then it prints fine.... but... if I input a number out of range then it terminates after the throw... still outputting the text "Number is out of range" with a core dump. Any ideas to why this is happening? If I"m doing this wrong... any recommendations as to how I can implement exceptions in this class?

Thanks in advance.
Well... are you catching the exception anywhere?
Well see I got this example out of the book. They didn't catch anything.

See, this is where I'm getting confused... if which is higher than MAX_EQUATIONS or less than 10 then what am I suppose to throw? My catch statements is suppose to be "cout << "Number is out of range" << endl. Urgh I don't know.... I'm really confused with these catch and throw statements.
then what am I suppose to throw?

An OutOfRange object, probably. Which is exactly what you're doing now.
If you throw something, you need to catch it somewhere, otherwise your program will die a disgraceful death.
Take a look at the Exceptions section of the C++ tutorial on this site. It will explain throwing and catching errors.
Quicklink:
http://cplusplus.com/doc/tutorial/exceptions/

I agree with the above. The C++ Tutoral's part on Exceptions should explain how to deal with exceptions in a somewhat graceful manner as well as the mechanics of at least a part of the exception-pitching process.

-Albatross
Last edited on
Topic archived. No new replies allowed.