Exceptions

In this program I am attempting to write a squaring program. The user enters an integer and it squares the number if it is a number greater than 0. I want to learn how to use the exception features in C++, and I have made an attempt on understanding them. I cannot get this code to give me the error message on line 33 when a number less than or equal to 0 is entered. Thanks for your help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>

using namespace std;

int number;
int squaredNumber;
int numberSquared;

int calculateSquare(int number)
{
	if (number <= 0)
	{
		throw  runtime_error("Error: This program cannot square zero.");
	}
	else
	{
		squaredNumber = (number * number);
	}
	return (squaredNumber);
}

int main()
{
	try
	{
		cout << "This is a program that will calculate the square of any positive" << endl;
		cout << "non-zero integer value." << endl;
		cout << "Enter a positive, non-zero value: ";
		cin >> number;
	}
	catch (exception &e)
	{
		cout << "Exception occured";
	}
	numberSquared = calculateSquare(number);
	cout << "The square of " << number;
	cout << " is " << numberSquared << endl;
	system("Pause");
	return 0;
}
Here is some updated code, I including the piece needed for runtime error, and remove the &e from 31

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <stdexcept>

using namespace std;

int number;
int squaredNumber;
int numberSquared;

int calculateSquare(int number)
{
	if (number <= 0)
	{
		throw  runtime_error("Error: This program cannot square zero.");
	}
	else
	{
		squaredNumber = (number * number);
	}
	return (squaredNumber);
}

int main()
{
	try
	{
		cout << "This is a program that will calculate the square of any positive" << endl;
		cout << "non-zero integer value." << endl;
		cout << "Enter a positive, non-zero value: ";
		cin >> number;
	}
	catch (exception)
	{
		cout << "Exception occured";
	}
	numberSquared = calculateSquare(number);
	cout << "The square of " << number;
	cout << " is " << numberSquared << endl;
	system("Pause");
	return 0;
}
lines 27-30 cannot throw exception at all (because streams do not throw exceprions by default)
line 26 can throw an exception, but there is nothing catching it.
I was going about this all wrong, I created an exception class and called it in my main function. I have figured this one out! thanks for your reply MiiNiPaa
Topic archived. No new replies allowed.