Friday, 12 June 2015

Java 8, easier with Cyclops : Try

Cyclops is another promising open source library from John McClean in AOL, that aims to extends and simplify Java 8 functionality.

One of its feature is Try that offers an alternative way to manage exception handling.

Imagine you have a method that load files from some location :

private List<File> loadFiles() { 
     return Lists.newArrayList(new File("somePath_one"), new File("somePath_two"));

Many things could go wrong there, file does not exist, network is down, etc.
Traditionally, we could have manage exceptions surrounding the loadFiles() method with try and catch and handle each exception within a catch statement.

Cyclops Try made things easier and cleaner :

Try.withCatch(this::loadFiles, Exception.class)

    .onFail(FileNotFoundException.class, e -> System.err.println("Something specific to do here if file does not exists" + e))

    .onFail(IOException.class, e -> System.err.println("Maybe retry a couple of times before dropping the operation" + e))


Based on the exception, different functions can be triggered.

No comments:

Post a Comment