aol / cyclops-integration

Home of the cyclops integration modules : support for Scala, Clojure, RxJava (1+2), Reactor, FunctionalJava, Guava, Dexx & Vavr
http://cyclops-react.io
MIT License
442 stars 51 forks source link

Use a finally #305

Closed laurent-thiebaud-gisaia closed 6 years ago

laurent-thiebaud-gisaia commented 6 years ago

Hi,

Sorry but can't find it in the documentation... How to perform a finally within a Try, eg.


Try.catchExceptions(IOException.class)
                            .run(() -> {
   ...
                            }).onFail((IOException e) -> {
                                throw new MyException(e);
                    });

Thx
johnmcclean commented 6 years ago

Hi @laurent-thiebaud-gisaia,

Best practice is to not throw Exceptions at all, but to use Try as a return type from your method instead (so the concept of finally outside of resource closing becomes less significant).

If the goal is to close a resource you can use Try.withResources.

e.g. the code below will clean up the BufferedReader calling close for you


Try.withResources(() -> new BufferedReader(new FileReader("file.txt")),
                                  this::read)

That is with cyclops X (com.oath.cyclops:10.0.1).

With older cyclops-try 7.2.4 the syntax is more like

Try.catchExceptions(FileNotFoundException.class,IOException.class)
                   .init(()->new BufferedReader(new FileReader("file.txt")))
                   .tryWithResources(this::read);

If you just want to run something no matter what (and throw the exception) you can use a fold (it's verbose). fold is called visit in cyclops 7.2.4


Try.runWithCatch(()-> run code ,IOException.class)
     .fold(i-> {
        this.myFinallyBlock(input);
        return i;
     },error ->{
      this.myFinallyBlock(input);
      throw new MyException(error);

   });
laurent-thiebaud-gisaia commented 6 years ago

OK thanks!