I can do this, no problem:
long lngval = 3L;
int i = lngval;
but if I try this:
try {
throw 3L;
}
catch(int i) {
cout << "caught " << i << endl;
}
I get an unhandled exception.
This seems inconsistent. what is the reason for no type conversion in this case?
In the first case, the compiler can tell exactly what you want to do: convert a
longto anint. In the second case, the compiler has to assume that you might have a construct like this:The idea is that the compiler can never know whether there might be a
catch (long l)lurking outside the current context, so it’s never safe to just pick the first possible conversion.This is also why it’s common to use a class hierarchy when throwing exceptions rather than random types like
intorlong: it makes it easy to add more or less specification to your exception handlers in such a way that the compiler can be sure of your intentions (via the is-a relationship).