Skip to content

Exception in thread “main” java.util.NoSuchElementException: No value present – How to fix?

NoSuchElementException would be thrown when you are trying to read a line/value that is not present in the source. One scenario would be when you try to read content from a specific line from a file, this exception would occur.

Exception in thread "main" java.util.NoSuchElementException: No value present
 at java.util.Optional.get(Optional.java:135)
Advertisements

To handle this just catch NoSuchElementException and return a proper message.

try {
	int lineNumber = 3;
	String str = Files.lines(Paths.get("/home/subash/Documents/sample.txt")).skip(lineNumber - 1).findFirst().get();
	System.out.println(str);
} catch (NoSuchElementException) {
	System.out.println("Element not found!");
} catch (Exception) {
	e.printStackTrace();
}
See also  Error: Could not find or load main class org.apache.maven.wrapper.MavenWrapperMainCaused by: java.lang.ClassNotFoundException: org.apache.maven.wrapper.MavenWrapperMain - How to fix?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.