Working with BufferedReader and it's variants in Java was always a bit of a pain: developers need to not to forget close it and do the IOException handing doing it, not to mention about bunch of null-checks. Otherwise you program work could be interrupted with the most surprising and unpleasant way possible.
Prior the Java 7 we had to do smth. like this:

Despite the null check the attempt to close the reader in finally still could throw an IOException so developers has to 1) close the reader and 2) handle possible error.

In Java 7 BufferedReader implements java.lang.AutoCloseable , so we are no longer forced to close it manually, but IOException still can be thrown, like this:

And finally Java 8 came along with all of it's might sugar. Now we have "try-with-resources" statement to help lazy developers and cover some resources access with the try/catch smart way and behind the scene. Code, using the Java 8 ability, would look like:

As you can see no try and no close() calls longer needed. Function throws IOException only because readLine() is called, if the internal logic of a function doesn't need it - this function wouldn't throw an error only because of buffered reader would close.






More like this

Get in touch

Get in touch

Frankfurt am Main, Germany (Sales)


Eckenheimer Schulstraße, 20

+38 (098) 630-49-85

Kharkiv, Ukraine (Development)


Trinklera street, 9

+38 (050) 908-31-07

Burgas, Bulgaria (Development)


бул. „Транспортна“ 15, Northern Industrial Zone

+359 877 350129