If Java returns NoSuchElementException

How to create an IF statement to check whether the function returns "NoSuchElementException"? Similar to what I have below

if (functionReturns == "NoSuchElementException")

Solution

If you mean that your function returns a string with NoSuchElementException, use equals instead of = =:

if("NoSuchElementException".equals(functionReturns)) { }

If you mean that your function can throw NoSuchElementException, use try catch When the function throws NoSuchElementException, the catch block will be triggered

try {
    function();
} catch(NoSuchElementException e) {
     //NoSuchElementException was thrown

}

If you mean that your function actually returns an instance of NoSuchElementException, you can use:

NoSuchElementException.class.isAssignableFrom(functionReturns)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>