i have this test code to handle exceptions in constructors.
function f() create an exception division by zero but this exception does not caught.
Instead if i throw a custom integer the exception is caught.
#include <iostream>
using namespace std;
class A
{
public:
void f(){
int x;
x=1/0;
//throw 10;
}
A(){
try{
f();
}
catch(int e){
cout << "Exception caught\n";
}
}
};
int main (int argc, const char * argv[])
{
A a;
return 0;
}
why i can catch the custom
throw 10;
and not the
x=1/0;
An Integer divided by zero is not an standard C++ exception. So You just cannot rely on an exception being thrown implicitly. An particular compiler might map the divide by zero to some kind of an exception(You will need to check the compiler documentation for this), if so you can catch that particular exception. However, note that this is not portable behavior and will not work for all compilers.
Best you can do is to check the error condition(divisor equals zero) yourself and throw an exception explicitly.