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.

 

 

 

Lego

Java
Development

More like this

Get in touch

Get in touch

Frankfurt am Main, Germany (Sales)

60354

Eckenheimer Schulstraße, 20

+38 (098) 630-49-85

info@a5.ua

Kharkiv, Ukraine (Development)

61023

Trinklera street, 9

+38 (050) 908-31-07

info@a5.ua

Burgas, Bulgaria (Development)

8008

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

+359 877 350129

info@a5.ua