0

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.

10
  • 2
    Your "solution" is obviously wrong. And so is the problem. What is wrong with using fstream directly? It's there to be used, not to be wrapped. Commented Jun 18, 2012 at 21:55
  • 2
    I would strongly advise against using inheritance here. If you're trying to mediate access to the file stream, just write a wrapper class around it so that you don't need to worry about these exceptions (you can just avoid calling exceptions). Using inheritance is problematic here. Commented Jun 18, 2012 at 21:56
  • The problem is that FileIO could change and could use WinApi to file i/o instead of std::fstream. In this current example I can avoid calling exceptions, but what if I use something else than std::fstream? Commented Jun 18, 2012 at 22:06
  • @Kele: Which is what fstream already does... are you under the impression that it does not use the Windows API under... Windows? fstream solved this problem already, what problem are you trying to solve exactly? Commented Jun 18, 2012 at 22:09
  • @EdS. That's just an example, I'm looking for a general solution. Commented Jun 18, 2012 at 22:10

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know what do you mean with 'this wheel'.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.