Apr 29, 2017 at 3:19pm UTC
I'm trying to understand try, throw and catch. And I ran into an issue with catching a float.
With this code I got a runtime error. Is it the compiler (MS visual studio 2015) or I'm I actually violating c++ rules?
int main(){
try {
throw 20.0;
}
catch (float i) {
std::cout << i;
}
return 0;
}
It tells me that my of type float has a value of -107374176.
placing a f behind 20.0. Or change catch(float i) into catch (double i).
It works fine.
int main(){
try {
throw 20.0f;
}
catch (float i) {
std::cout << i;
}
return 0;
}
Apr 29, 2017 at 3:30pm UTC
20.0
is a double
, not a float
, and so catch (float i)
can't catch it. An uncaught exception is a runtime error.
20.0f
is a float
, so catch (float i)
can catch it.
Normal C++ code throws library exception types: throw std::runtime_error("stuff happened" );
and catches them by their common base type catch (const std::exception& e) { std::cout << e.what() << '\n' ; }
Last edited on Apr 29, 2017 at 3:31pm UTC
Apr 29, 2017 at 3:49pm UTC
Thank you very much. it is very helpful.
I did run a check to deepen my understanding.
std::cout << sizeof(20.0)
//becomes 8, therefore double
std::cout << sizeof(20.0f)
//becomes 4 therefore float
Apr 29, 2017 at 4:08pm UTC
A better way to check that in general might have been
1 2 3
# include <type_traits>
...
static_assert (std::is_same<decltype (20.0), double >::value, "20.0 is not a double" );
Because there is no guarantee that different types don't have the same size.
Last edited on Apr 29, 2017 at 7:08pm UTC
Apr 29, 2017 at 6:03pm UTC
That's not pedantic at all, and you're totally right. I'm afraid I have been making that mistake consistently....
FWIW, I was very glad that in C++17 you can omit the error message as in a normal assert().
Fixed ;)