I have a pair of files, say Foo.cpp
and Foo.hpp
that define a class, say Foo
. Foo
's methods have the potential to throw an exception, defined in the file MyException.hpp
, but Foo.hpp
does not need MyException
.
Obviously the .cpp
needs to include the exception header, but should I include the exception header in Foo.hpp
instead to allow any files that use Foo
to have a definition of the exception?
The usual rule of thumb is that every file should include the headers that it needs. So, no, don't add MyException.hpp
to Foo.hpp
unless it's needed there. Code that deals with your exception class should #include "MyException.hpp"
. So, obviously, whichever files implement the member functions that throw this exception need to include "MyException.hpp"
, and any files that include code that catch this exception also need it.
I assume you derive your custom exception from std::exception.
Now there are two use cases (I imagine):
Most of the exceptions I have seen are informative, there is nothing to resolve the state of objects affected.
It is considered a good style to make each .h
file self-sufficient , so that each header would include/provide all features it needs. Given that, it makes sense to include MyException.hpp
in Foo.hpp
. That way, users of Foo.h
will not endure compile-time errors when they just include it in their code.
Only include the MyException.hpp header in you Foo.hpp file. Let your Foo.cpp include only the Foo.hpp header. The .cpp file is only meant for the implementation of the interface declared in the header file. The .cpp should not contain any other includes part from it's own header.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.