This is the third post about my experiments with a fluent I/O API. This post covers how the API enhances exception handling.
Eliminating unnecessary catch blocks
This code compresses a string into an array of bytes:
The try/finally block is necessary. This ensures that the general
contract for stream handling is honoured. If the
implementation acquired native resources, this would ensure that they
However, it is difficult to conceive of a reasonable situation in
IOException would occur in this code.
This code eliminates the
IOException handling by
Note that this code does not swallow exceptions. If an
were thrown, it would be wrapped in the API's
Runtime exception handling
The problem with checked exceptions is in interacting with methods that don't declare them. Consider this code to write an exception trace to a file:
PrintWriter will swallow any exceptions thrown
by the underlying streams. The boolean isn't a great error handling
mechanism: it doesn't expose any useful information; if you pass the
off to something else, you have to wait until when it passes it back to
your code to check it.
By having an underlying stream that catches the
and throws it as a runtime exception, we can get and throw the
I/O and checked exception handling is likely to become more of an issue with Java 7 and lambda support.
- Part 1: introduction
- Part 2: extending the API
- Part 3: error handling
- Part 4: conclusions and downloads
Comments & criticism are welcome.