2005-09-23

Java exceptions

Recently there has been a hot discussion about Java vs. C (well, these discussions always seem hot) on sci.crypt. I have also given my contribution to the discussion.

The discussion concentrates on exceptions vs. error codes for error handling. I think that, in most cases, error codes are the better solution. Read the article for the explanation.

However, there I've started an idea on which I'd like to elaborate in more detail here. There are many problems with the naive use of exceptions, and this article gives an introduction to exception safety and exception guarantees.

To summarize the article shortly, one of bigger problems is that throwing an exception can leave your object in an inconsistent state. This is not only C++ problem, it is a problem in any language that provides exceptions, including Java and Python. So why not borrow transactions from RDBMS and introduce them in the programming language?

Consider the following artificial example (in some pseudo, C-like language):

x = 2;
begin {
// some mutating code
++x;
throw some_exception;
}

The transaction consists of everything within begin{}. When execution "cleanly" falls over the closing brace, the transaction is commited. If an exception is thrown within the begin{} block, then all changes to any member variables of the object done within the transaction are "rolled-back". In the above example, the x will be reverted to value 2.

Some open questions:
  • What to do static variables within transaction blocks,
  • should nested transactions be allowed,
  • implementation issues,
  • performance considerations.

No comments: