I found that there are three ways to catch an exception, what are the differences?
1) catch by value;
2) catch by reference;
3) catch by pointer;
I only know that catch by value will invoke two copies of the object, catch by reference will invoke one. So how about catch by pointer? When to use catch by pointer? In addition to throw an object, can I throw a pointer to an object like this?
class A {}
void f() {
A *p = new A();
throw p;
}
The recommended way is to throw by value and catch by reference.
Your example code throws a pointer, which is a bad idea since you would have to manage memory at the catch site.
If you really feel you should throw a pointer, use a smart pointer such as shared_ptr
.
Anyway, Herb Sutter and Alexei Alexandrescu explain that really well in their C++ Coding Standards book which I paraphrased.
See C++ Coding Standards: Throw by Value, Catch by Reference.