Exception not throwing

Jul 27, 2016 at 4:37pm
Hello everyone. I've created a simple conversion code with an exception handler but the exception isn't throwing with a negative number. Any ideas?

//code:
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <iomanip>

using namespace std; 

double LengthCentimeters (double);

class NegativeNumber
{};

int main() 
{ 

double inches; // number of inches 
double centimeters; // number of centimeters 
char ContinuationFlag = 'Y';

	while (toupper(ContinuationFlag) == 'Y')
	{ 
	// process inches to centimeters 

	cout<<"Enter length in inches:"<<endl; 
	cin>>inches;
	cout<<endl;

	//To convert from Inches to Centimeter, simply multiply 
	// the Inches by 2.54 

	//begin throw,try and catch commands-- 

	try
		{ 

		centimeters = inches*=2.54f; //total number of centimeters in an inch 
		cout << "The length in centimeters is:" << centimeters << endl;
		}
	catch (NegativeNumber)
		{
	cout << "Number cannot be negative!" << endl;
		}

cout << "Do you want to convert more lengths?" << endl;
	cout << "Enter 'Y' or 'N'" << endl;
cin >> ContinuationFlag;
	}
return 0;
}
double LengthCentimeters ( double InputInches)
{
	if(InputInches<=0) 
	{
	throw NegativeNumber(); 
	}
return (InputInches*=2.54f);

}

if I put a negative number into the prompt, it spits out a number instead of the exception. Help?
Last edited on Jul 27, 2016 at 5:02pm
Jul 27, 2016 at 4:49pm
Maybe call the function that throws instead of not calling it?
Jul 27, 2016 at 4:51pm
1) Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/z13hAqkS/

2) You don't actually call LengthCentimeters() anywhere. So nothing's throwing that exception.
Jul 27, 2016 at 5:30pm
Thank you MikeyBoy! Changed line 34 to
 
Centimeters = LengthCentimeters ( Inches);

And the NegativeNumber class exception is throwing now. Appreciate it!
Jul 28, 2016 at 9:58am
You're welcome - glad it worked out.
Topic archived. No new replies allowed.