Dealing with Exceptions

Java programmers are quite opinionated about checked exceptions. Irrespective of how we feel about them, checked exceptions are here to stay and we have to deal with them. Let’s look at some options for working with them in the context of lambda expressions.

In the next example we create a lambda expression that invokes a method that potentially throws a checked exception. We take a list of path names and ask for their canonical path using the getCanonicalPath method.

 
public​ ​class​ HandleException {
 
public​ ​static​ ​void​ main(​String​​[]​ args) ​throws​ IOException {
 
Stream.of(​"/usr"​, ​"/tmp"​)
 
.map(path -> ​new​ ​File​(path).getCanonicalPath())
 
.forEach(​System​.out::println);
 
//Error, this code will ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.