I wrote this calculator code and it's working fine, but I wanted to ask if I'm doing the error-handling fine or not. As it is now, the program will exit immediately after the exception handling code is done, but I'm wondering if that's fine for this program. [Note: as of Chapter 3, exceptions still haven't been introduced yet, but I already know about them so I decided to use them.]
// chap3_ex10.cpp : Defines the entry point for the console application.
// Osman Zakir
// 5 / 24 / 2016
// Programming: Principles and Practice using C++ 2nd Edition Chapter 3 Exercise 10
// This is a very simple calculator. Only accepts one operation and two numbers
#include "std_lib_facilities.h"
double get_number();
string get_operaton();
double calculate_result(constdouble x, constdouble y, const string& operation);
void print_result(constdouble result);
int main()
{
try
{
cout << "Enter a number: ";
double x = get_number();
cout << "Enter another number: ";
double y = get_number();
cout << "Enter an operation: ";
string operation = get_operaton();
double result = calculate_result(x, y, operation);
print_result(result);
keep_window_open();
}
catch (const runtime_error& r)
{
cerr << r.what() << "\n";
keep_window_open();
return 1;
}
catch (const exception& e)
{
cerr << e.what() << "\n";
keep_window_open();
return 2;
}
catch (...)
{
cerr << "Error: Unexpected exception caught\n";
keep_window_open();
return 3;
}
}
double get_number()
{
double number = 0;
cin >> number;
cin.ignore(32767, '\n');
return number;
}
string get_operaton()
{
string operation;
cin >> operation;
cin.ignore(32767, '\n');
return operation;
}
double calculate_result(constdouble x, constdouble y, const string& operation)
{
if (operation == "+")
{
return x + y;
}
elseif (operation == "-")
{
return x - y;
}
elseif (operation == "*")
{
return x * y;
}
elseif (operation == "/")
{
return x / y;
}
elseif (operation != "/" || operation != "*" || operation != "+" || operation != "-")
{
error("Invalid operation!");
}
}
void print_result(constdouble result)
{
cout << "Your answer is: " << result << "\n";
}
The library access header for the book, std_lib_facilities.h, has iostream and stdexcept, as well as the file that defines std::numeric_limits, among other important header files. I could bring it here for anyone who needs it, but this post is already going to get too long so I'll have to do that in another post.