C++: Throwing exceptions, use 'new' or not?


Answers

unless there is some special requirement not to, I always throw by value and catch by const reference. This is because the new itself could throw an exception as well, during error handling, it is best to avoid things which can cause exceptions.

Question

Is it proper to use throw new FoobarException(Baz argument); or throw FoobarException(Baz argument);?

When catching I always use catch(FoobarException& e) "just in case" but I never could find a solid answer whether I had to use new or not in C++ (Java definitely) or if it was just a preference of the programmer.




How does the memory leak happen?

The exception is your leak. You are instantiating it and not deleting. Look at this





Tags