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?
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.
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.
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.
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.
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.
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