There is a method get(sql) (I can not modify it). This method returns MyObjects and it has to be in try catch block because JqlParseException is possible there. My code is:
String sql = something; try{ MyObject object = get(sql); } catch(JqlParseException e){ e.printStackTrace(); } catch(RuntimeException e){ e.printStackTrace(); } I want to remove try catch and use Optional class, I tried:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(RuntimeException::new); but IDE force there try catch too. And for:
MyObject object = Optional.ofNullable(get(sql)).orElseThrow(JqlParseException::new)); is an error (in IDE) The type JqlParseException does not define JqlParseException() that is applicable. Is there any way to avoid try catch blocks and use optional?
get, see if it saysthrows JqlException. If it does, you must use try...catch.Optional] focuses on getting rid of those endless null checks. I'd be more specific. Many people would jump to the conclusion that they ought to replace all occurrences ofnullwithOptional, which goes against the intent ofOptional's designers.nullcan't be replaced withOptional, except in performance critical code or there is a design flaw. Please point out a situation, except those listed above, wherenullis used butOptionalis not applicable.Optionalfields or parameters. As Brian Goetz puts it, [their] intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and usingnullfor such was overwhelmingly likely to cause errors. See also this great talk by Stuart Marks.