Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Where to throw exception?

I have some kind of an ideological question, so:

Suppose I have some templated function

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

which does something with this object and the stream (for example, serializes that object to the stream or something like that).

Let's say I also add some plain wrappers like (and let's say the number of these wrappers equals 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 the exception if my stream is bad? Should I do this in each wrapper or just move that check to my Foo, so that it's body would look like

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

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

Thank you.

like image 327
Yippie-Ki-Yay Avatar asked Dec 18 '25 18:12

Yippie-Ki-Yay


2 Answers

In this case it's better to throw it in the lower-level Foo function so that you don't have to copy the validation and exception throwing code in all of your wrappers. In general using exceptions correctly can make your code a lot cleaner by removing a lot of data validation checking that you might otherwise do redundantly at multiple levels in the call stack.

like image 76
bshields Avatar answered Dec 20 '25 08:12

bshields


I would prefer not to delay notifying an error. If you know after you have created the stream, that it is no good, why call a method that works on it? I know that to reduce code-redundancy you plan to move it further down. But the downside of that approach is a less-specific error message. So this depends to some extent on the source-code context. If you could get away with a generic error message at the lower-function level you can add the code there, this will surely ease maintanence of the code especially when there are new developers on the team. If you need a specific error message better handle it at the point of failure itself.

To avoid code redundancy call a common function that makes this exception/error for you. Do not copy/paste the code in every wrapper.

like image 23
Abhay Avatar answered Dec 20 '25 06:12

Abhay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!