Exceptions

This is supposed to be a basic program that calculates the area of a rectangle but has a catch statement if one or of the dimensions (length, width) is less than or equal to zero.

Questions
1. Am i doing this even remotely correctly?
2. I get this compiler error and don't know why:
[Directory]:17:1: error: expected unqualified-id
catch (badArea) {
^


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
//I include too much, I know, my text book asks me to do it for now
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
int getArea(int, int);
class badArea {};

int main() {
	int w = 2, x = 0, y = 1, z = -1;
	int area = getArea(w, x);
	int area2 = getArea(y, z);
	int area3 = getArea(w, y);
	double ratio = area/area3;
}

catch (badArea) {
	cout << "Bad argument to area? (negative value?)";
}

int getArea(int l, int w) {
	if(l<=0 || w<=0) throw badArea();
	return l * w;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
   try{
      //code that may throw an exception
   }
   catch(bardArea&){ //why catch a reference http://stackoverflow.com/questions/2023032/catch-exception-by-pointer-in-c
      //code that handles the exception
   }
   catch(another_kind_of_exception&){
      //...
   }
   catch(...){ //catches anything
      //...
   } 
}//note that main() ends here 
ne555

You beat me to it. I was messing with the code heyyouyesyou posted.

@heyyouyesyou

Thank you for posting this. I learned while try to solve it. I learned that although stack unwinding happens the compiler does not allow you to depend on it. Meaning you need a catch block for every try block and vice-versa as demonstrated by ne555.
This still doesn't make sense to me. I don't know what the & sign is, my book hasn't gotten there. (Though, I think I've seen it before, does it have to do with pointers?)
http://www.cplusplus.com/doc/tutorial/pointers/

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

int getNum(int);

int main() {
	
	int num;

	std::cout << "Enter an integer: ";
	std::cin >> num;
	std::cout << std::endl;

	try{
		std::cout << getNum(num) << std::endl;
	}
	catch (std::runtime_error &e){
		std::cout << e.what() << std::endl;
	}

	return 0; 
}

int getNum(int x){

	if (x <= 0)
		throw std::runtime_error("Value cannot be less than or equal to 0.");

	return x;
}
Topic archived. No new replies allowed.