Java If NoSuchElementException is returned
How can I make an if statement to check if the "NoSuchElementException" is returned from the function?
If you meant that your function returns String
with a value as NoSuchElementException, use equals
instead ==
:
if("NoSuchElementException".equals(functionReturns)) { }
If you meant that your function can throw
a NoSuchElementException
, use try-catch
. The block catch
will fire when the function throws a NoSuchElementException
.
try {
function();
} catch(NoSuchElementException e) {
//NoSuchElementException was thrown
}
If you meant that your function actually returns an instance NoSuchElementException
, you can use:
NoSuchElementException.class.isAssignableFrom(functionReturns)
source to share
First of all NoSuchElementException
or whatever Exception
is mostly thrown away by the not Returned method. So you can / shouldn't type-check it return
. The best approach for handling any type Exception
is try catch
. Example: -
try {
// Probable Exception Throwing code
} catch(NoSuchElementException e) {
// handle/log specific type of error
}
catch(Exception e) {
// handle/log Generic error if none specific is defined
}
Read more about Exception
in Official Docs here
source to share
if you use an if statement then more than one error must be thrown, so in java 7 In Java 7 it became possible to catch multiple different exceptions in one catch block. This is also known as multiplayer capture.
Before Java 7, you should write something like this:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(NoSuchElementException e) {//work as if if (functionReturns == "NoSuchElementException")
logger.log(e);
} catch(NoSuchElementException1 e) {//work as if if (functionReturns == "NoSuchElementException1")
logger.log(e);
} catch(NoSuchElementException2 e) {//work as if if (functionReturns == "NoSuchElementException2")
logger.severe(e);
}
As you can see, both NoSuchElementException1 and NoSuchElementException2 are handled the same way, but you still have to write two separate catch blocks for them.
In Java 7, you can catch multiple exceptions using the multiple catch syntax:
try {
// execute code that may throw 1 of the 3 exceptions below.
//combind way to catch multiple error
} catch(NoSuchElementException1 | NoSuchElementException2 e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Note that the two exception class names in the first catch block are separated by a pipe character. The nature of the pipe between exception class names is how you declare multiple exceptions to be caught by the same catch clause.
source to share