28 July 2012

Exception handling

Hi all, today I am going to write about a renowned topic, namely, exception handling. Exception is a means for indication of a deviation from the normal execution flow of the program, though it can always be expected and handled appropriately.
    To indicate such a deviation we need to generate an exception. For this purpose the throw keyword is used. It needs an object as an argument which will represent the exception. This could be either an object of a built-in or a user-defined type:

throw int();
throw MyClass();

As soon as throw statement is executed the execution leaves the current scope and starts to seek a “corresponding” handler. A handler is introduced by means of catch keyword which also needs the type of the exception to be handled:

catch (int)
{
       // .. handle the exceptional situation
}

catch (MyClass)
{
       // .. handle the exceptional situation
}

To handle the exception with catch statements the dangerous code (a piece of code that may throw an exception) should be placed in a try block:

try {
       // dangerous code with possible exception
}

So the final scenario is as follows:

try {
       // .. some code
       throw objectOfMyClass;
       // .. maybe some more code
}
catch (MyClass)
{
       // .. handle the exceptional situation
}

All these things are to provide a little understanding of what goes on. Now let’s get deeper and see everything in more details. The try block usually does not contain the throw statement directly. Instead, it contains a function call and that function includes either a throw statement or another function call with throw statement. I.e., the throw statement can be nested any number of levels.

As soon as an exception is thrown something known as stack unwinding happens, i.e. all the local objects (not static and not extern) on the stack in the current stack frame are destroyed (destructors are called). If the throw statement is immediately in the try block, then only the objects declared in the block will be destroyed, otherwise, if throw is in a function body, first the destructors of all local object allocated on the stack in that function body are called, then only the ones in try block. After that the exception object is copied to be passed to a handler body and the execution continues from the “corresponding” handler. Where the copied object is kept is unspecified. If no handler is found for the exception, std::termintate() function is called from <exception> header. The same happens (std::terminate() call) if an exception is thrown while unwinding the stack. That's why it is not recommended to have unsafe code in destructors, because if a local object of that type is created its destructor will be called during stack unwinding and the second throw statement will bring to program termination. We will get back to std::terminate() soon, but now let’s understand what a “corresponding” handler is.

Usually, an exception handler not only specifies the type of the exception to be caught, but also introduces a variable which the exception object will be assigned to. This is done because exceptions as a rule contain information about what went wrong, why, or any other user-defined info, at least exceptions also are class objects, so anyone can define his/her own exception classes. So the handler looks like this:

catch (MyClass ex) {
       // handle the exception or
       // inform about failure in a friendly manner
}

Actually it is not a good practice to use the type itself, as it will copy the exception object into the locally introduced variable. So to avoid this overhead, we can catch the exception by reference similar to passing arguments to functions. Here we go:

catch (const MyClass& ex) {
       // handle the exception or
       // inform about failure in a friendly manner
}

The const keyword may be omitted, but rarely one would want to modify the thrown exception object. To catch an exception one need not specify the exact type of the thrown object. The same exception can be caught by a handler which expects an object of parent types, for example:

try {
       throw Derived();
}
catch (const Base& ex) {
       // ... handle here
}

Note, that this is possible only in case of public inheritance. If the Base is a protected or a private base of Derived, then the handler will not catch the exception. Now if we expect several types of exceptions in a hierarchy we need to handle the most specific (derived) ones first:

catch (const Derived& ex) {
       // exception of type Derived is handled here
}
catch (const Base& ex) {
       // exception of type Base is handled here
}

If we change the order of handlers, then the second one (expecting exceptions of type Derived) will never be reached, as the first one will handle exceptions of both Base and Derived types. Modern compilers should at least warn about this.

As you see, the number of handlers is not limited. We already know that the handlers with exact type or with base types are “corresponding”. To learn about other possible correspondence, see the clause 15.3.3 of C++ standard specification.

Exception handlers can also be nested. For example if one handler catches an exception of type T1 and throws another one of type T2, there could be a handler of type T2 inside the former one, as follows:

catch (const T1& ex) {
       // try to handle T1
       // if could not throw T2
       try {
              throw T2();
       } catch (const T2& ex) {
              // handle T2 here
       }
}

If we want to handle some exceptions which may raise from constructor body we can add try-catch blocks there. But if we want to handle the exceptions coming from the constructor initialization list, then the syntax changes a little. Here is what it looks like:


class MyClass : public Base
{
private:
       SomeType mem;

public:
       MyClass(const SomeType& arg)
              try : Base(), mem(arg)
       {
              // Any exception thrown from initialization list
              // or from c'tor body can be handled below.
       }
       catch (...)
       {
              // A handler should follow the c'tor body.
       }
};

It is possible, that a piece of code tries to handle the exception, but if it does not manage to, it re-throws the exception, as if this piece of code never existed. Other handlers in different parts of system may try to handle the exception and so on. In order to achieve this effect we again refer to the same throw keyword, but this time without any parameters:

catch (const T1& ex) {
       // ... try to handle the exception
       // if unable just rethrow
       throw;
}

You might ask why don't we re-throw just throwing the caught exception object (“throw ex;”)? Well, throw; throws the originally thrown object, which means:
  • it does not copy the exception object one more time as opposed to “throw ex;
  • it does not change the type of exception. What we caught is not necessarily what was thrown, so if we throw what we caught, the type of exception may be different. See the example below:

try {
       throw Derived();
}
catch (const Base& ex) {
       // The exception rethrown below is copied
       // and it has type Base, not Derived
       throw ex;
}

If we replace the last line in handler body with “throw;” the original exception of type Derived will be re-thrown.

The keyword throw has another application either. It is exception specification. This is a way to specify what types of exceptions may a function throw:

void f1() throw(); // does not throw at all
void f2() throw(int); // may throw only int
void f3() throw(Base, int); // may throw Base and int

If the function throws an exception of not specified type, std::unexpected() is called which by default calls std::terminate(). A little later about this as I already promised. We will not get much into the throw specifications as they are deprecated in C++11. For similar purpose the noexcept keyword has been introduced in C++11, which can be used either as an operator or a specifier. You can find the details on the web, but here is a brief explanation.
  • noexcept specifier specifies whether the function throws exceptions or not. It can be used with or without expression argument. If an expression is evaluated to true, then the function should not throw exceptions. Otherwise, it may. noexcept without expression argument is equivalent to noexcept(true). If a function marked with noexcept throws an exception, std::terminate() is called.
  • noexcept operator is always used with a constant expression, and performs a check whether the expression is specified as noexcept. Note that this is a compile-time check.


The specifier and operator are often used together in generic codes, for example:

template <class Container>
int my_func(const Container& c, int index) noexcept(noexcept(Container::operator[]))
{
       return c[index];
}

If the Container’s operator[] is marked with noexcept then the operator will return true, and my_func will also be noexcept, otherwise it will not.

The time has come to talk about std::terminate() and std::unexpected(). As stated above std::unexpected() is called when a function throws an exception inconsistent with its throw specification (remember this is deprecated in C++11). By default std::unexpected() in its turn calls std::terminate(). And std::terminate() by default invokes std::abort() which stops the program execution without calling destructors for any constructed object. Nevertheless, we are free to substitute this functions with our owns. There are two typedefs in <exception> header:

typedef void (*unexpected_handler)();
typedef void (*terminate_handler)();

These are just pointers to functions accepting no arguments and returning nothing. And there are two functions which make it possible to override what std::unexpected() and std::terminate() call with our own functions:

unexpected_handler set_unexpected(unexpected_handler f) throw();
terminate_handler set_terminate (terminate_handler f) throw();

In C++11 both functions are marked with noexcept specifier instead of empty exception specification. Both functions return the currently set handlers. This is good for keeping the current handlers to temporarily substitute them with our owns and then restore again. Though in C++11 it is possible just to call std::get_unexpected() or std::get_terminate() to retrieve current handlers.

There are many exception classes in standard library <exception> header. The most general one is std::exception itself. And all the others derive from it. It has one public virtual function, which returns a human-readable message about the exception:

virtual const char* what() const;

So you can call what() on any exception from standard library. There is also a set of predefined exception classes in <stdexcept> header.

That’s it. There are many things that you’ll learn experimenting with exceptions. I cannot remember and write here all the things, but I hope this post gives a good understanding of how the exception handling mechanism works and how you can modify it. Thanks for your precious time.

18 July 2012

Command pattern implementation

Hi dear reader! As my PhD defense day had passed, I have a lot more time than some weeks ago, so I will be posting more often. Maybe not all the posts will be much interesting, or interesting for many people, but still they will be useful for some. This time I'm going to write about Command pattern implementation, the most simple, indeed.

As a little foreword, I want to say that most of the design patterns are very acceptable in terms of logic, many people are using them every day, but they are not aware that this small techniques or ideas are called patterns and have their specific names. The basic idea behind many patterns is decoupling the components of the system, or just the interacting/communicating objects. So that it is easy to replace them separately, to add new features, to make available dynamic (run-time) decision-making, to avoid compiling the whole code after a small change, etc.
    So command pattern is meant for decoupling the command as a separate executable from the object it is bound to, i.e. treating the command as an object per se, not as an action. The most common examples of this are menus and toolbars, where each item executes a command, and this command is just a separate object bound to item. Besides the decoupling there is one more big plus in this approach - one can bind the command to as many items as wanted (this reminds about flyweight pattern but its another topic). So let's go ahead and start looking into details.

What we should have to look into details is:
  • a command - the action to be executed
  • an invoker - this can be anything starting from a button, a menu or toolbar item up to some callback manager, or a thread pool.
  • a receiver - this should be the object the command acts upon
It's obvious that we need three different objects, thus, three different classes for the above list to exist. As far we have an only requirement from the command : it should be executable. Unless we know how it should be executed, or what it should do we can provide just an interface with a single pure virtual function:

class Command
{
public:
       virtual void Execute() = 0;
};

The receiver should be able to do something, so that the command can act upon it. So let's take a simple class with single method doing something.

class Receiver
{
public:
       void Action()
       {
              std::cout << "Command received" << std::endl;
              // don't forget to include <iostream> header
       }
};

Now we need an invoker to invoke the command. It should know which command to invoke, so should somehow keep a reference to the command. The key point here is that the invoker should not care about how the command will execute, what it should act upon, and what it should do at all. So it uses the provided interface above and just calls the Execute() function as seen below.

class Invoker
{
       Command *m_command;

public:
       Invoker(Command *cmd = 0) : m_command(cmd)
       {
       }

       void SetCommad(Command *cmd)
       {
              m_command = cmd;
       }

       void Invoke()
       {
              if (0 != m_command)
              {
                     m_command->Execute();
              }
       }
};

Note the SetCommand() function which lets to bind another command to the Invoker at run-time, so we are free to decide which command should be invoked by the current invoker.

What else do we need to test the system? A command. Actually we have provided an interface, but we don't have a concrete type to instantiate. So we need a concrete command with Execute() function body defined. Here we go:

class MyCommand : public Command
{
       Receiver *m_receiver;

public:
       MyCommand(Receiver *rcv = 0) : m_receiver(rcv)
       {
       }

       void SetReceiver(Receiver *rcv)
       {
              m_receiver = rcv;
       }

       virtual void Execute()
       {
              if (0 != m_receiver)
              {
                     m_receiver->Action();
              }
       }
};

Let's look what we have in MyCommand. The implementation of Execute() method, which is a simple call to Receiver's Action(). Thus we decoupled the command from the real action it does under hood, binding a receiver to a command. The SetReceiver() function makes it easy to bind another receiver to the command. Actually this would be more meaningful if we had an abstract receiver class (interface with single Action() method) and then derived concrete receivers, which would act to the same command in an intrinsic way, but this does not change the essence.

So now we can test our command.

int main()
{
       Receiver r;
       MyCommand cmd(&r);
       Invoker caller(&cmd);
       caller.Invoke();

       return 0;
}

As we expected the command has been invoked. We've reached our goal. So what we get ? We get a freedom to change/remove the command of the invoker, we can change the receiver, all this at run-time. Now about compilation, if we have our interfaces in one module and we create some new commands in another, we don't need to rebuild the first one to use the new commands. Feel free to improvise on this scheme. This is all for this time, thank you for your time and interest.


11 July 2012

Passing arguments by value, by pointer and by reference

Hi again, today I am going to "speak" about very very familiar topic - argument passing. Almost every tech interview has a question like why do we pass an argument by reference, or what to do when passing an object as a parameter to avoid copying, and so on. I want to tell a little on how the argument passing is handled and what everyone should know.

For our examples let's write a small class with one member of type int and two methods for retrieving that member and also for retrieving the object address. Here we go:


class my_type
{
       int value;

public:

       my_type() : value(11)
       {
       }

       int get_value() const
       {
              return value;
       }

       const void * get_address() const
       {
              return this;
       }
};


Let's start from the very easy case: passing arguments by value.
To pass an argument by value we need to specify the argument type in the function declaration as follows:


void by_value(my_type arg)
{
       std::cout << "Value: " << arg.get_value() << std::endl;
       std::cout << "Address: " << arg.get_address() << std::endl;
}


Now let's try it.


int main()
{
       my_type m;
       std::cout << "Original Value: "
                       << m.get_value() << std::endl;
       std::cout << "Original Address: "
                       << m.get_address() << std::endl;
       by_value(m);

       return 0;
}

I compiled and executed this code and got the following output:
Original Value: 11
Original Address: 0043FB38
Value: 11
Address: 0043FA64
Press any key to continue . . .


As you see the addresses of original object and the argument differ, but the values are the same. So most probably the object has been copied when passing as an argument, more precisely the function argument holds a copy of the original passed object. We can go further and make sure that the object is really copied just by declaring a copy constructor in the private section of the class my_type. If you compile then, the compiler will complain on the by_value function call line, as it is trying to copy the object.

So our conclusion is that passing argument by value always copies the original object.
Now let's go to the next case: passing arguments by pointer.


To pass an argument by pointer the function signature should have a 'pointer to the type of object' as a parameter type, i.e.

void by_pointer(my_type *pointer)
{
       std::cout << "Value: " << pointer->get_value() << std::endl;
       std::cout << "Address: " << pointer->get_address() << std::endl;
}



Now we are going to call this function.

int main()
{
       my_type m;
       std::cout << "Original Value: "
                       << m.get_value() << std::endl;
       std::cout << "Original Address: "
                       << m.get_address() << std::endl;
       by_pointer(&m);

       return 0;
}

The output of the execution is as follows:
Original Value: 11
Original Address: 003DFD3C
Value: 11
Address: 003DFD3C
Press any key to continue . . .


So now the value is the same, and the address is the same either, thus, we can state that the object has not been copied this time. To make sure we again add a private copy constructor to the class body and rerun. No problem this time, as the function does not need to copy the passed in object. Good for now. So what happened really? Let's modify the code a little to see the details. What I will do now is just add a line of code in by_pointer function body to print out also the address of the pointer itself:

std::cout << "Pointer address: " << &pointer << std::endl;

Also we need to update the code in main to see the address of the original pointer, but as we cannot take the address of the rvalue we should create a pointer explicitly. So the modified main function body follows:

my_type *mp = new my_type;
std::cout << "Original Value: "
   << mp->get_value() << std::endl;
std::cout << "Original Address: "
   << mp->get_address() << std::endl;
std::cout << "Address of original pointer: "
   << &mp << std::endl;
by_pointer(mp);

return 0;

Now the output of the execution will be the following:
Original Value: 11
Original Address: 002BD9F0
Address of original pointer: 0024FD70
Value: 11
Address: 002BD9F0
Pointer address: 0024FC7C
Press any key to continue . . .


As you see the object is not copied, but the pointer to the passed object is. So if we consider the pointer itself the passed argument we can again state, that the passed argument is copied. The object is not what we passed as an argument therefore it is not copied.

The last case is passing argument by reference. As the compiler treats the reference as an alias for the referring object, so we cannot write a code to check whether the reference differs from the object. Maybe one can check it in the assembly code, but I am not good at it, so I will just bring up the idea of how this case is handled.

To pass an argument by reference you need to specify the type as reference to the type of argument using the ampersand ('&') symbol:

void by_ref(my_type& ref)
{
       // do something
}


The call of the function will look exactly the same as in the call-by-value case. If we again modify main function and execute, we will see that the object again is not copied (again make a private copy constructor). Any function should know its arguments' locations in memory to be able to access them, so it means that passing by reference is almost the same as passing by address. The reference is treated as an alias but actually it holds the address of an object. So in this case also, the reference is copied to the function arguments, to learn the undergoing details, look through the assembly code or search more on this topic on the internet, but the idea is given here.

Thus, the conclusion is: the passed argument is copied, no matter whether the argument is an object, a reference or a pointer. Note, that I don't say "whether it is passed by value, by pointer or by reference". I hope some people will find something new for them in this post, and the others will just revise what they already know. Thank you for visiting my blog and your time spent reading this article.

6 July 2012

A simple implementation of Observer (Listener) pattern

I was just writing an example and I thought it might be interesting for some people. So I decided to post it here. What the Observer pattern resembles, I think most of you know. The same pattern with probable little modifications is known as Listener, Signal/Slot, Event Handling, etc. The idea is that one object somehow lets another object or objects know about some change (mouse click, text edited, some member data updated, a row deleted from the table in database, etc.). This action is called notification, so an object notifies another object about the change. The latter - another object - is called a listener, or a handler, or an observer, etc.

The main point to consider is that the notifier should somehow keep the references of the listeners, otherwise the latter will never know about the change. But how is it possible? For first, let's admit that the notifier does not care much of whoever is observing it. It has its own functionality, and it acts as expected, it is out of its responsibilities to find the listeners and ask whether they are interested in some specific changes. So the listeners themselves know what they want to listen to, what they need to observe, and it is their own responsibility to register/subscribe for the updates from interesting objects. Thus, the notifier should only provide a mechanism for listeners to register for notifications. As soon as the listener is registered, the notifier can easily let know it about any interesting change. Ok, good for now.

But, what does it mean "to let know"? It means that each listener registering for notifications from the notifier should itself provide a method for being notified. For this purpose all the listeners should have a common interface (IListener in the sample code). Now seems everything can be properly done. Here is the schema again:

1. all the listeners are derived (can provide a common interface in another ways also) from an abstract base IListener
2. the notifier provides methods for listeners to register/unregister
3. the notifier keeps a collection of registered listeners
4. each time a change occurs, the notifier lets all the registered listeners know by means of their own method provided by the common interface (HandleNotification() in this example)
5. HandleNotification() is a member function of the listener so the latter can react to the notification as needed.

Here is a code sample for the above solution:

#include <iostream>
#include <set>
#include <algorithm>

class IListener
{
public:
       virtual void HandleNotification() = 0;
};

class Notifier
{
protected:
       virtual void Notify()
       {
              std::for_each(m_listeners.begin(), m_listeners.end(), [&](IListener *l) {l->HandleNotification(); });
       }

public:
       virtual void RegisterListener(IListener *l)
       {
              m_listeners.insert(l);
       }

       virtual void UnregisterListener(IListener *l)
       {
              std::set<IListener *>::const_iterator iter = m_listeners.find(l);
              if (iter != m_listeners.end())
              {
                     m_listeners.erase(iter);
              } else {
                     // handle the case
                     std::cout << "Could not unregister the specified listener object as it is not registered." << std::endl;
              }
       }

private:
       std::set<IListener*> m_listeners;
};


For a more practical example of using the classes above, see the code below:

class Button : public Notifier
{
public:
       void Press()
       {
              Notify();
       }
};

class TextBox : public IListener
{
public:
       TextBox() : num(0)
       { }
private:
       int num;
      
private:
       virtual void HandleNotification()
       {
              std::cout << "The button has been pressed " << ++num << " times" << std::endl;
       }

};

int main()
{
       Button b1;
       TextBox t1;
       b1.RegisterListener(&t1);
       b1.Press();

       return 0;
}