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; }
std::exception_ptr is a nullable pointer-like type that manages an exception object which has been thrown and captured with std::current_exception. An instance of std::exception_ptr may be passed to another function, possibly on another thread, where the exception may be rethrown and handled with a catch clause.
An exception should be caught by reference rather than by value. The analyzer detected a potential error that has to do with catching an exception by value. It is much better and safer to catch exceptions by reference. Catching exceptions by value causes two types of issues.
C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.
Exception-specificationsAll the smart pointer templates contain member functions which can never throw exceptions, because they neither throw exceptions themselves nor call other functions which may throw exceptions.
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.
Catch follows normal assignment compatibility rules, that is, if you throw a value, you can catch it as value or reference, but not as pointer; if you throw a pointer, you can catch it only as a pointer (or reference to a pointer...).
But it doesn't really make sense to throw pointers, it will only cause memory management headaches. Thus, you should, in general follow the rule throw by value, catch by reference, as explained by Gregory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With