TITLE: catch by reference or by value (Newsgroups: comp.lang.c++.moderated, 15 Sep 98) KASERSKI: "Marcin Kasperski" > I get used to: > > catch (ExceptionClass exc) { > .... > } > > but recently I've seen somewhere > > catch (ExceptionClass& exc) { > } > > I can also imagine catching const &. > > Could anyone compare those methods (esp. their efficiency)? > > PS. I know people, who decided to throw and catch pointers. What about this > method? HOPPS: khopps@Adobe.COM (Kevin J. Hopps) The issues are much like those involved in setting the types for function parameters, with one important difference noted below. Objects that are thrown as exceptions will be copied to some place that is implementation-specific. It is perfectly safe to throw an object that lives on the stack because it will be copied. Catching by value means that the object will be copied again to the local catch block. Catching by reference will require one less copy. As for the difference between catching by reference vs. catching by const-reference, obviously you cannot modify the caught object if the const-reference is used. It shouldn't matter outside the scope of the handler, unless the object is rethrown. I am not sure what the standard requires when rethrowing an object caught by reference or const-reference -- will it make another copy or reuse the existing copy? An important difference between function parameter types and throw/catch types is in the use of pointers. When calling a function, it is perfectly safe to pass it the address of local data, because that data is guaranteed to be in scope during the life of the function called. However, when throwing an exception, the scope at the throw point is gone when control reaches the handler, so passing the address of local data is a bad idea. Sometimes the convention is used that the pointer thrown points to a dynamically allocated object, and the handler deletes it. IMHO this is dangerous for at least two reasons. 1) There is a very good chance of a resource leak, and 2) This convention makes the error reporting mechanism itself susceptible to out-of-memory conditions (how do you report an out-of-memory error if you need memory to report it?). OTOH, one handy convention for quick-and-dirty error handling is to throw and catch static character strings, e.g. throw "can't open database"; [snip]