Papipone Papipone - 11 months ago 59
C++ Question

C++ throwing exceptions (need advices)

I was reading The C++ Programming Language by bjarne Stroustrup, especially chapters about exception safety and RAII programming idiom. I am familiar with RAII, but not with the throw of exceptions. Actually, I do not see the throw keyword used very often. I saw it sparingly (vector, red/black tree, ...) when I studied the Standard Template Library in order to understand the template mechanisms and the RAII idiom.

If I was to use the throw keyword, I would be tended to use it all the time. Thus, this syntax implies the use of the try-catch clauses which make the code looks ugly.

What do you think about this? Are there better techniques to handle exceptions? Or should I absolutely use throw?

Thanks for your responses.

Answer Source

First of all, these links might help a bit. Link 1 Link 2

Most of the time, C++ exceptions are better suited that any alternative. And actually, I think it makes the code prettier. I will give you an example, and I hope you understand.

Assume I have to load a model, and prepare it to be rendered(I know you probably are not familiar with graphics programming, but you should get the point) on the screen. This means I have a big function or at least a big one that calls a couple of other smaller ones. The whole process includes opening a model file, reading all coordinates, opening material files, allocating memory for materials, opening texture files, allocating memory for textures, loading the texture etc. A lot of stuff.

But sometimes, at the very end, I might encounter an error where I cannot find one of the texture files, or cannot open it. How to handle it? Have the small file open function return a value to the texture loading function who checks it, realizes something bad happened and in turn returns something to the function that read the main model file etc? Don't you think all that returning, checking and freeing resources at each point looks ugly?

Here is a better way: wrap the load_model() function in a try block, and just insert some throw statements wherever you need them. And have all the "free memory" code in the catch section. It will look a lot cleaner, and is also less likely you will make a mistake.

I hope you understand the idea. If you have any questions, please ask them.