I'm still learning C++ and I'm trying to implement exception handling using a try-catch block.
#include<iostream>
#include<cstdlib> //for exit
const int divide_flag(-1);
double divide(double x, double y){
if(x==0) throw divide_flag;
return y/x;
}
int main()
{
double x{3.},y{4.};
double result;
try{
result=divide(x,y);
std::cout<<"y/x = "<<result<<std::endl;
x=0;
result=divide(x,y);
std::cout<<"y/x = "<<result<<std::endl;
}
catch(int error_flag) {
if(error_flag == divide_flag) {
std::cerr<<"Error: divide by zero"<<std::endl;
exit(error_flag);
}
}
return 0;
}
The code compiles fine but when I run it the program aborts after the exception is thrown and does not enter the catch block. The only output I get is
y/x = 1.33333
Abort trap: 6
I'm compiling with g++ on Mac and I'm not sure why the catch block is never entered.