Many people consider exceptions to be a problem because they create invisible paths through your code. For example in this snippet:
function writeToFile(text, filename):
filehandle = open(filename)
foreach line in text:
filehandle.write(line)
filehandle.close()
The write
method could throw an Exception. In that case the function will end prematurely and the filehandle is not closed. Writing exception safe code is hard.
On the other hand adding explicit error handling like in C clutters up the code considerably. (This seems to be the "other" option if you don't like exceptions.)
function writeToFile(text, filename):
filehandle = open(filename)
if nullptr == filehandle:
return
foreach line in text:
if(!filehandle.write(line)):
filehandle.close()
return
filehandle.close()
Now this is just a simple example. I just wrote code to do some logging and between the abstract concept of "Just dump data into a file!" and my implementation is a difference of about 200 lines.
So what do people do to keep their code readable in spite of all those corner cases that they need to watch out for and handle?
Do we have to resort to literate programming? :)