java - Method wrapper for dealing with Exceptions? -


i'm implementing iterator , in order deal exceptions i'm using following pattern: actual work done in private hasnextpriv() method whereas hasnext() method deals exceptions. reason doing way because don't want litter hasnextpriv() try-catch blocks.

@override public boolean hasnext() {     try {         return hasnextpriv();     } catch (xmlstreamexception e) {         e.printstacktrace();         try {             reader.close();         } catch (xmlstreamexception e1) {             e1.printstacktrace();         }     }     return false; } 

questions:

  1. is there better way this?
  2. what name private method hasnextpriv()?

another way handle exceptions extract each part throws exception in small pure function handles each exception. , construct final result composing functions.

optional<resource> open() {     try{          //...          return optional.of(resource);     } catch {          //....          return optional.empty();     } }  optional<value> read(resource resource) {     try{          //...          return optional.of(resource.value);     } catch {          //....          return optional.empty();     } }  boolean hasnext() {      open().flatmap(this::read).ispresent(); } 

there no need return optional everywhere. there dummy value in null object pattern


another pattern wrap function execution in object produces either result or error value. in library javaslang looks like

return try.of(this::hasnextpriv)     .recover(x -> match(x).of(         case(instanceof(exception_1.class), /*handle exception*/),         case(instanceof(exception_2.class), ...)))     .getorelse(false); 

try object similar java 8 optional instead of holding present value or missing value try contains value of either success or failure.


regarding naming hasnextpriv in case there specific domain of data structure. come more specific name hasmorenodes or notempty etc.


Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -