When to choose between throwing exceptions or returning return codes?

21 hours ago 3
ARTICLE AD BOX

This question is brought about by the below examples. I have approached a couple of people for their opinions, but still would like some more help and context from the general community.

Here is an example in C++ with some pseudo-code:

class ImageFile : File { vector<char> contents; public: int write(const vector<char> v) { if (v contains something other than a, b, or c) { return ReturnValues::INVAID_INPUT; } this->contents = move(v); return ReturnValues::SUCCESS } }; ImageFile img_file{"name_of_image_file"}; vector<char> v{'a', 'b', 'c', '99'} img_file.write(v);

Using this approach, write() fails silently, so it makes sense to do:

int return_value = img_file.write(v); if (return_value != SUCCESS) { // Do something }

I was curious if, instead of using return values, what if an exception was thrown? So that write() will still fail, but by allowing an exception to fall through main(). This would, at least, remove the risk of silent failures.

One of my professors told me that return codes are the usual method in C++, and that it doesn't really matter so long as one follows a project's guidelines. However, I would like some input on your experience and opinion.

Read Entire Article