How it works...

In our application, we defined a custom class called Error that we are going to use when throwing and catching exceptions. This class provides a constructor, a copy constructor, and a destructor that only logs information to the console. We need it to evaluate the efficiency of different exception catching approaches.

The Error class only contains the code data field, which is used to differentiate between instances of the class:

class Error {
int code;

We evaluate three approaches for exception handling. The first one, CatchByValue, is the most straightforward. We create and throw an instance of the Error class:

throw Error(1);

Then, we catch it by value:

catch (Error e) {

The second implementation, CatchByPointer, creates an instance of Error dynamically using the new operator:

throw new Error(2);

We use a pointer to catch the exception:

catch (Error* e) {

Finally, CatchByReference throws an exception similar to CatchByValue, but it uses a const reference to Error when catching it:

catch (const Error& e) {

Does it make any difference? When we run our program, we get the following output:

As you can see, when catching an object by value, a copy of the exception object was created. Though not critical in a sample application, this inefficiency can cause performance issues in a high-load application. 

There is no inefficiency when catching exceptions by pointer, but we can see that the object destructor was not invoked, causing a memory leak. This can be avoided by calling delete from the catch block, but this is error-prone since it is not always clear who is responsible for destroying an object referenced by a pointer.

The reference approach is the safest and most efficient one. There is no memory leak and unnecessary copying. Also, making the reference constant gives the compiler a hint that it is not going to be changed and thus can be better optimized under the hood.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.230.82