Reputation: 3
I want to make a FileIO class which will provide some methods like write or read. Also I want to hide the implementation of FileIO (currently, it just derives from std::fstream). The problem is that std::fstream could throw some exceptions but I don't want my FileIO class to throw std::fstream exceptions, I want to throw my own (e.g. FileIO::SomethingBadHappened). Is there an elegant way to do this?
My solution is to just rewrite every method of std::fstream with an additional try/catch block.
EDIT: FileIO class is just an example. I'm looking for a general solution for wrapping an arbitrary class.
Upvotes: 0
Views: 162
Reputation: 308176
There's no way around it - you have to put a try/catch block around any function call that can generate an exception if you want to rethrow a different exception.
Rather than using inheritance, you should use encapsulation - have your class own an object that you can propagate your calls to. This allows you to simplify your interface, only providing the capabilities needed and thus not needing to wrap every single method of the underlying class that does the work.
Upvotes: 0
Reputation: 101456
The "elegant" way to do this is to not reinvent the wheel. Especially this wheel, which has traveled to and from the Moon thousands of times. It's tried and true. You don't need to invent this there.
Upvotes: 3