My program invokes methods that will set errno when a failure occurs, I throw errno like an exception and catch it:
try
{
if (-1 == truncate("/foo/bar.txt", 0))
{
throw errno;
}
}
catch (const int errno)
{
//log
}
Here I don't want to discuss the exception handling best practice topic. The truth is in the code above, catch block will not hit when the variable name in catch bracket is errno. This issue can be simplified to:
try
{
throw 1999;
}
catch (const int errno) //renaming "errno" to "e" works!!!
{
//unreachable code here
}
I know errno is a "special" name, but I thought C++ could handle same variable names defined in different scopes correctly.
//test.h
int my_number = 99;
//test.cpp
#include "test.h"
int main()
{
try
{
throw 1999;
}
catch(int my_number)
{
std::cout << "in catch: " << my_number << std::endl; //prints 1999
}
std::cout << my_number << std::endl; //prints 99
}
The program is compiled in GNU5.4(happens in both C++11 and C++14). Can anyone explain the strange behavior?
errno is a macro. So your exception handler contains some expanded tokens that most likely make very little sense. From the standard ([errno]):
The contents of the header are the same as the POSIX header , except that errno shall be defined as a macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With