Exception Handling

My code seems to work fine for the maximum size, which is 39, but not for the minimum.

Problematic function:
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
void Diamond::SetSize(const int diamondSize)
{
	try
	{
	if(diamondSize < MINIMUMSIZE) throw diamondSize;
	else
	{
		size = diamondSize;
		cout << "Value is within RangeA\n";
	}
	}	
	catch(int e)
	{
		size = MINIMUMSIZE;
		cout << "Size was set to " << MINIMUMSIZE << ".\n";
	}
	
	try
	{
	if (diamondSize > MAXIMUMSIZE) throw diamondSize;
	else
	{
		size = diamondSize;
		cout << "Value is within RangeB\n";
	}
	}
	catch(int e)
	{
		size = MAXIMUMSIZE;
		cout << "Size was set to " << MAXIMUMSIZE << ".\n";
	}

	}

Constructor:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//Constants:
const char LOWERBOUND='!';
const char UPPERBOUND='~';
const char DEFAULTBORDER='*';
const char DEFAULTFILL='#';
const int MINIMUMSIZE=1;
const int MAXIMUMSIZE=39;
//
////in class->Diamond(const int size, const char border = DEFAULTBORDER, const char fill = DEFAULTFILL);
Diamond::Diamond (const int size, const char borderchar, const char fillchar)
{
	SetSize(size);
	SetBorder(borderchar);
	SetFill(fillchar);
}

main:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main() 
{
  // set decimal outputs to 2 decimal places
  cout << setiosflags( ios::fixed | ios::showpoint )
	<< setprecision( 2 );

  // create some Diamonds
  Diamond d1( -5 ), d2( 7, '^' ), d3( 5, ' ', ' ' ), d4( 50 , '$' , 'o');
  // display original Diamonds
  cout << "d1 has size = " << d1.GetSize() << " units.\n";
  d1.Draw();
  cout << "\nd2 has size = " << d2.GetSize() << " units.\n";
  d2.Draw();
return 0;
}


Any help or tips would be awesome!
I'd have to ask why are you using exceptions like this?
Exception handling adds quite a lot of overhead to the application. In this case you could just use if-else statements.

Anyways, you need to re-order your logic slightly otherwise both checks get done and you get duplicate outputs.

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
#include<iostream>

using namespace std;

void F(const int N) {
	const int MAX = 100;
	const int MIN = 50;

	try {

		if (N > MIN && N < MAX) {
			cout << "N is ok at " << N << endl;
		} else
			throw N;

	} catch (const int ex) {
		if (ex < MIN)
			cout << "N is below MIN at " << N << endl;
		else
			cout << "N is above MAX at " << N << endl;
	}
}


int main () {

	F(75);
	F(101);
	F(40);

    return 0;
}
Well, for one, you're trying to manipulate the value of size- which is not only just a value passed to the constructor, then to SetSize, but also a constant. So... you can't actually manipulate the value, for both reasons (why would you manipulate the value of a passed variable, anyway?). Do you have size initialized anywhere else in the code?
Topic archived. No new replies allowed.