Added error handling. There is a bug for empty databases due to the flow control. Will be fixed on next commit.