Java如果返回NoSuchElementException

Sou*_*ode 3 java if-statement

如何创建if语句来检查函数是否返回"NoSuchElementException"?类似于我下面的东西.

if (functionReturns == "NoSuchElementException")
Run Code Online (Sandbox Code Playgroud)

CKi*_*ing 6

如何创建一个if语句来检查函数是否返回NoSuchElementException?

如果您的意思是您的函数返回String值为NoSuchElementException,请使用equals而不是==:

if("NoSuchElementException".equals(functionReturns)) { }
Run Code Online (Sandbox Code Playgroud)

如果你的意思是,你的函数可以throw一个NoSuchElementException,使用try-catch.catch当函数抛出一个时,将触发该块NoSuchElementException.

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

}
Run Code Online (Sandbox Code Playgroud)

如果你的意思是你的函数实际上返回了一个实例NoSuchElementException,你可以使用:

NoSuchElementException.class.isAssignableFrom(functionReturns)
Run Code Online (Sandbox Code Playgroud)