It is my understanding that all exceptions in c++ ultimately extend exception. In Java world, catching Exception e would have worked regardless of the type of Exception. How is this done in C++?
Why is that in this snippet exception is not caught?
try{
int z = 34/0;
cout << "This line should not appear" << endl;
} catch (exception e) {
cout << "An error has occurred: " << e.what(); // Not executed
}
Also, in C++, how can one find out what actions causes what exception?
An integer divided by
0is not a standard c++ exception. So no exception is thrown in this case what you get is an plain Undefined Behavior.Some specific compilers might map this scenario to an particular exception and you will have to check your compiler documentation to find the same.However, using such a feature will be non-portable and your code will be restricted to your specific compiler.
The best you can do in such a scenario is to check the error condition(divisor equals zero) yourself and throw an exception explicitly.
The
std::exceptionclass provides a methodstd::exception::what()specifically for this.