C ++ - Where to throw an exception?

I have some kind of ideological question, therefore:

Suppose I have a template function

template <typename Stream>
void Foo(Stream& stream, Object& object) { ... }

which does something with this objectand stream(e.g. serializes this object for a stream or something like that).

Let's say I also add some simple wrappers, for example (and let the number of these wrappers be 2 or 3):

void FooToFile(const std::string& filename, Object& object)
{
   std::ifstream stream(filename.c_str());
   Foo(stream, object);
}

So my question is:

Where in this case (ideologically) should I throw an exception if mine is streambad? Should I do this in every shell or just transfer this check to mine Fooso that the body looks like

if (!foo.good()) throw (something);
// Perform ordinary actions

I understand that this may not be the most important part of coding, and these solutions are actually equal, but I just don't know the “right” way to implement this.

Thank.

+3
5

Foo, . , , .

+5

. , , , , ? , . . , - . , , , , , . , .

, , / . .

+2

, . , . try catch, .

:

int count = 0;
bool isTrue = false;
MyCustomerObject someObject = null;

try
{
   // Initialise count, isTrue, someObject. Process.
}
catch(SpecificException e)
{
// Handle and throw up the stack. You don't want to lose the exception.
}
+1

:

struct StreamException : std::runtime_error
{ 
    StreamException(const std::string& s) : std::runtime_error(s) { }
    virtual ~StreamException() throw() { }
};

void EnsureStreamIsGood(const std::ios& s)
{
    if (!s.good()) { throw StreamException(); }
}

void EnsureStreamNotFail(const std::ios& s)
{
    if (s.fail()) { throw StreamException(); }
}

, .

+1

Traditionally, in C ++, stream operations do not throw exceptions. This is partly due to historical reasons, and partly due to interruptions in streaming, errors are expected. A way to use the standard C ++ stream classes is to set a flag in the stream to indicate that an error has occurred, which user code can be checked. Not using exceptions makes resuming (which is often required for threading) easier than if exceptions were thrown.

+1
source

Source: https://habr.com/ru/post/1748867/


All Articles