Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

catch exception by pointer in C++

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;   } 
like image 601
skydoor Avatar asked Jan 07 '10 19:01

skydoor


People also ask

What is exception pointer?

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.

Should I catch by reference instead?

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.

Can you catch exceptions in C?

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

Do smart pointers throw exceptions?

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.


2 Answers

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.

like image 138
Gregory Pakosz Avatar answered Oct 12 '22 01:10

Gregory Pakosz


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.

like image 43
oefe Avatar answered Oct 12 '22 01:10

oefe