To use exception handling properly, you need an exception class, and another class that the program uses. When runtime errors occur in your program's class, you need to throw() your exception. Then somewhere in your program the exception should be handled with a try/catch block.
And besides that, you included standard exceptions, but you're not using them. If I wrote your code, I would use it.
Here's an example for you to work with.
Code:
#include <iostream>
#include <stdexcept> // my compiler's exception header
class DevideByZero : public std::exception {
public:
// inherited constructor, destructor, and copy
virtual const char *what() const throw() {
return "Cannot devide by zero!";
}
};
class Execution {
public:
// default contructor, destructor, and copy
double Calculate(const double A, const double B, const char Operator)
throw(DevideByZero);
};
double Execution::Calculate(const double A, const double B, const char Operator)
throw(DevideByZero) {
double result = 0.;
switch(Operator) {
case '+':
result = A + B; break;
case '-':
result = A - B; break;
case '*':
result = A * B; break;
case '/':
if (0 == B)
throw(DevideByZero());
else result = A / B;
break;
default:
result = -1.; break;
}
return result;
}
int main(void) {
try {
Execution math_problem;
std::cout<<"Two plus three is: " << math_problem.Calculate(2, 3, '+') <<
std::endl;
std::cout<<"Seven divided by zero is: " << math_problem.Calculate(7, 0, '/') <<
std::endl;
}
catch (DevideByZero& e) {
std::cout << e.what() << std::endl;
}
std::cin.get();
return 0;
}
Just to be clear, if your functions' signature has a throw(type) statement in it, this tells the compiler that you want to limit the function's exceptions down to a certain type. In my example, I allowed Calculate to throw only DevideByZero exceptions because I was confident that it would be the only type of exception. If you write throw() in a function's signature, you are telling the compiler that the function will never throw any exceptions.
Constructors and destructors should also never throw exceptions.
I will answer your questions if you have any!