Two functions, hmean() and gmean(), either of which can throw exceptions that are caught in the same catch block. How can I identify which of the 2 functions has thrown the exception while continuing to use a single catch block? Code below:
Code:
#include<iostream>
#include<stdexcept>
#include<cmath>
using namespace std;
class exp_catch: public logic_error{
public:
exp_catch(double x, double y, const char *s = "Logic error exception thrown!!!"):m_x(x), m_y(y), logic_error(s){}
void hmean() throw(logic_error);
void gmean() throw (logic_error);
void show_val();
private:
double m_x;
double m_y;
};
int main(){
exp_catch e1(10, -12);
try{
e1.hmean();
e1.gmean();
}
catch(logic_error & le){
cout<<le.what()<<endl;
e1.show_val();
}
}
void exp_catch::hmean() throw (logic_error){
if(m_x == -m_y){
throw *this;
}
double z = (2 * m_x * m_y) /(m_x + m_y);
cout <<"Harmonic mean is: "<<z<<endl;
}
void exp_catch::gmean() throw(logic_error){
if (m_x < 0 || m_y < 0){
throw *this;
}
double z = std::sqrt(m_x * m_y);
cout<<"Geometric mean is: "<< z<<endl;
}
void exp_catch::show_val(){
cout<<"The input values are: "<<m_x<<" and "<<m_y<<endl;
}
Thank you