Throw catch in namespaces implementation

Question Deleted: obtuse. Answers given were too acute Or did not hit on the spot for such obtuse questioning.

Answers


The golden rule when using exceptions in C++ is "throw by value, catch by const reference".

In quotient(), when you say

throw new string("divide by zero!");

you're creating a new string on the heap which is never freed if an exception occurs. Instead, you should just say

throw string("divide by zero!");

which will stack-allocate a new string instead.

Later, when in your catch block, you should catch by const reference, i.e.

catch (const string& str) {
    // ...
}

The reason for this is mostly technical: a const reference can bind to an rvalue whereas a mutable reference cannot, and catching by value might require a copy of string.

Or perhaps looking at it another way: the purpose of an exception is to communicate the reason that something failed. That reason is not going to to change once it's happened, so the exception should be treated as const after creation.


Need Your Help

Rails 4: should tmp/cache be under version control?

ruby-on-rails ruby-on-rails-4 caching

I'm assuming no, since according to this post it's unnecessary, but would there be any advantages (for example, when deploying to production) to keeping it in version control?