1

As the title says, what is the difference between these 2 ways of throwing an exception?

void method1() {
  //...
  throw new MyException();
}

void method2() {
  //...
  throw "my exception";
}

I am afraid of memory leaks.

In method1 who must free the memory allocated by new?

In method2, is the string allocated on the heap (again who frees it?)? Or is it passed like a return value on the stack?

Kami
  • 1,079
  • 2
  • 13
  • 28

1 Answers1

3

There are many reasons to throw by value and catch by reference

If you throw a pointer to dynamic memory, you'll have to manually deal with memory management on the catch site.

As proposed in the c++ coding standards :

If you feel you really must throw a pointer, consider throwing a value-like smart pointer such as a shared_ptr<T> instead of a plain T* .

Nikos Athanasiou
  • 29,616
  • 15
  • 87
  • 153