I was trying to demonstrate exception handling and came across an oddity I can't solve. The problem arises in the following code:
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
double sqrt(double x) {
if ( x < 0 ){
throw invalid_argument("sqrt received negative argument");
}
return sqrt(x);
}
int main(int argc, char *argv[]) {
try {
double s = sqrt(-1);
}
catch (const exception& e) {
cout << "Caught " << e.what() << endl;
}
return 0;
}
The code fails:
terminate called after throwing an instance of 'std::invalid_argument'
what(): sqrt received negative argument
./dostuff.sh: line 8: 3472 Aborted (core dumped) ./may_22.exe
If, however, I either change the name of the sqrt function I write to "mySqrt", or remove the header, the exception is properly caught. Any idea what is causing this?
I'm compiling via
g++ -g -Wall -std=c++0x -Weffc++ may_22.cpp -o may_22.exe
with g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1
EDIT: To clarify, this does not seem like a namespace issue. The code is clearly calling my sqrt function, as shown by the exception message.
EDIT 2: This code still fails to handle the exception for me.
#include <iostream>
#include <cmath>
#include <stdexcept>
double sqrt(double x) {
if ( x < 0 ){
throw std::invalid_argument("sqrt received negative argument");
}
return std::sqrt(x);
}
int main(int argc, char *argv[]) {
try {
double s = sqrt(-1);
}
catch (std::exception& e) {
std::cout << "Caught " << e.what() << std::endl;
}
return 0;
}