When I have a number of expressions that can throw an exception, for example:
instanceObj.final_doc_type = instance.getFinalDocument().getValue().getType().getValue();
instanceObj.final_doc_date = instance.getFinalDocument().getValue().getDate().toGregorianCalendar().getTime();
instanceObj.appeal_date = instance.getFinalDocument().getValue().getAppealDate().getValue().toGregorianCalendar().getTime();
...
instanceObj.start_doc_type = instance.getStartDocument().getValue().getDocType().getValue();
instanceObj.apeealed_type = instance.getStartDocument().getValue().getApeealedType().getValue();
instanceObj.declarers_list_mult_id = instance.getStartDocument().getValue().getDeclarers().getValue().getString();
...
is there any method to handle these expressions by some one function that will return some default value (or null) IF a parameter is invalid and throws an exception - this can take place if, for example:
instance.getFinalDocument().getValue().getDate() = null
So that I don't need to surround each expression with try-catch block or check every point for null.
Use
Optional.map
:This sets
final_doc_type
tonull
if anything in the chain isnull
.If you only want to set its value in the case of a non-null value, remove the assignment, and change the
orElse
toifPresent
: