I want to do some exception handling. I plan on using the __LINE__ and __FILE__ macros.
I have some header Vectors.hpp in which I implement some class for a vector structure. In this class I implement the operator [] and I want to throw an exception each time this operator is used with an out of bounds index. I test this class in some source test.cpp. I want then to be able to see the exact line in test.cpp where this happened.
However I know that the __LINE__ macro is disabled every time you include some header, so what I got is the line in Vectors.hpp where I handle the exception and not the line in test.cpp. Is there a nice way to get around this? Or, how would one implement his own __LINE__ macro?
The
__LINE__macro is never disabled. It is expanded where you write it. There are two ways to write code (more precisely, there are two ways to produce tokens):If you have it is some file
foo.cpplike this (just exemplary, that’s very bad code actually)then
__LINE__is always 3 and__FILE__is alwaysfoo.cpp.That’s because the macros are expanded where they are used. The solution would be to find a way to get them expanded where you want it, and the only way to do so is to define another macro:
But as you see, this leads to quite ugly code and workarounds.
Real Solution: Just throw an exception upon out of bounds (
throw std::out_of_range), or do it like the standard library:If your user receives an exception, he is ought to debug where he/she/it made a programming error.