Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

java - Throw exception in optional in Java8

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?

question from:https://stackoverflow.com/questions/42993428/throw-exception-in-optional-in-java8

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Optional is not intended for the purpose of dealing with exceptions, it was intended to deal with potential nulls without breaking the flow of your program. For example:

 myOptional.map(Integer::parseInt).orElseThrow(() -> new RuntimeException("No data!");

This will automatically skip the map step if the optional was empty and go right to the throw step -- a nice unbroken program flow.

When you write:

 myOptionalValue.orElseThrow(() -> new RuntimeException("Unavailable"));

... what you are really saying is: Return my optional value, but throw an exception if it is not available.

What you seem to want is a way to create an optional (that instantly catches the exception) and will rethrow that exception when you try using the optional.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...