Try...catch...throw or ifs?

This is a discussion on Try...catch...throw or ifs? within the C++ Programming forums, part of the General Programming Boards category; I'm still a complete newbie in C++, and i've been wondering... Which is a better way to catch exceptions? using ...

Try...catch...throw or ifs?

I'm still a complete newbie in C++, and i've been wondering... Which is a better way to catch exceptions? using try-catch-throw, or some nested ifs?
Because, at least for me, the try-catch-throw syntax seems really confusing, and I don't see how i could implement it on big functions/classes without making a mess out of my code.

Exceptions are not necessarily better. It depends on the situation. I don't understand what you mean by try/catch/throw versus nested ifs.

Basically, you should use exceptions if the error is not common or expected. For example, if you have a list of objects and that list should never be empty, then you can throw an exception if you end up with an empty list in code that requires its data. Also, you shouldn't be catching exceptions all over your code. You should only catch the exception where your code handle handle it properly, otherwise, let it automatically move up the call stack. You should probably never catch an exception thrown in the same function.

BTW, you can derive your exceptions from std::exception, and you should catch exceptions by reference, not by value.

It's the same as passing objects to functions. It is better to pass a non-simple type by const reference to a function rather than by value to avoid an unnecessary copy. Same way with exceptions where a complex object is thrown. I should have made it clear that catching simple types like int by value is fine like the tutorial shows. For bigger objects, catching by value makes an unnecessary copy.

As far as why you can catch the derived classes using the base class name, it is the essence of polymorphism. If you understand why it is done that way with functions, then you'll understand why that is done with exceptions.