Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ catch blocks - catch exception by value or reference? [duplicate]

Possible Duplicate:
catch exception by pointer in C++

I always catch exceptions by value. e.g

try{ ... } catch(CustomException e){ ... } 

But I came across some code that instead had catch(CustomException &e) instead. Is this a)fine b)wrong c)a grey area?

like image 646
Mr. Boy Avatar asked Mar 26 '10 09:03

Mr. Boy


People also ask

Why is it preferred to catch exceptions by reference instead of by value?

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.

Can one catch blocks efficiently trap and handle multiple exceptions?

In Java 7, catch block has been improved to handle multiple exceptions in a single catch block. If you are catching multiple exceptions and they have similar code, then using this feature will reduce code duplication.

What happens if exception occurs in catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

Can exceptions be caught by multiple catch blocks in any order?

At a time only one exception occurs and at a time only one catch block is executed. All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.


1 Answers

The standard practice for exceptions in C++ is ...

Throw by value, catch by reference

Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException which inherits from CustomException and overrides items like an error code. If a MyException type was thrown your catch block would cause it to be converted to a CustomException instance which would cause the error code to change.

like image 133
JaredPar Avatar answered Oct 07 '22 17:10

JaredPar