Implement exception hierarchy

Implement exception hierarchy and add some tests.