Java value not set exception

How to Fix java.util.NoSuchElementException in Java?

An unexpected, unwanted event that disturbed the normal flow of a program is called Exception. Most of the time exceptions are caused by our program and these are recoverable. Suppose if our program requirement is to read data from the remote file locating in the U.S.A. At runtime, if a remote file is not available then we will get RuntimeException saying fileNotFoundException. If fileNotFoundException occurs we can provide the local file to the program to read and continue the rest of the program normally.

There are mainly two types of exception in java as follows:

1. Checked Exception: The exception which is checked by the compiler for the smooth execution of the program at runtime is called a checked exception. In our program, if there is a chance of rising checked exceptions then compulsory we should handle that checked exception (either by try-catch or throws keyword) otherwise we will get the compile-time error. Examples of checked exceptions are ClassNotFoundException, IOException, SQLException, etc.

2. Unchecked Exception: The exceptions which are not checked by the compiler, whether programmer handling or not such type of exception are called an unchecked exception. Examples of unchecked Exceptions are ArithmeticException, ArrayStoreException, etc.

Whether the exception is checked or unchecked every exception occurs at run time only if there is no chance of occurring any exception at compile time.

NoSuchElementException:

Читайте также:  Параметры функции range python

It is the child class of RuntimeException and hence it is an unchecked exception. This exception is rise automatically by JVM and given by the accessors methods of Enumeration, Iterator or Tokenizer such as next() or nextElement() or nextToken() when we are trying to access the content of an array, collection, or any other object and if these objects are empty or if we are trying to get next element after reaching the end of an object then we will get java.util.NoSuchElementException.

In the below example we are trying to access a HashMap by using the accessor method next() of the Iterator class but as the HashMap is empty we will be going to get NoSuchElementException.

Источник

Как понять NullPointerException

Эта простая статья скорее для начинающих разработчиков Java, хотя я нередко вижу и опытных коллег, которые беспомощно глядят на stack trace, сообщающий о NullPointerException (сокращённо NPE), и не могут сделать никаких выводов без отладчика. Разумеется, до NPE своё приложение лучше не доводить: вам помогут null-аннотации, валидация входных параметров и другие способы. Но когда пациент уже болен, надо его лечить, а не капать на мозги, что он ходил зимой без шапки.

  1. Его кинули с помощью throw
  2. Кто-то кинул null с помощью throw
  3. Кто-то пытается обратиться по null-ссылке
  1. Вызов нестатического метода класса
  2. Обращение (чтение или запись) к нестатическому полю
  3. Обращение (чтение или запись) к элементу массива
  4. Чтение length у массива
  5. Неявный вызов метода valueOf при анбоксинге (unboxing)
 1: class Data < 2: private String val; 3: public Data(String val) 4: public String getValue() 5: > 6: 7: class Formatter < 8: public static String format(String value) < 9: return value.trim(); 10: >11: > 12: 13: public class TestNPE < 14: public static String handle(Formatter f, Data d) < 15: return f.format(d.getValue()); 16: >17: >
Exception in thread "main" java.lang.NullPointerException at TestNPE.handle(TestNPE.java:15)

В чём причина исключения — в f, d или d.val? Нетрудно заметить, что f в этой строке вообще не читается, так как метод format статический. Конечно, обращаться к статическому методу через экземпляр класса плохо, но такой код встречается (мог, например, появиться после рефакторинга). Так или иначе значение f не может быть причиной исключения. Если бы d был не null, а d.val — null, тогда бы исключение возникло уже внутри метода format (в девятой строчке). Аналогично проблема не могла быть внутри метода getValue, даже если бы он был сложнее. Раз исключение в пятнадцатой строчке, остаётся одна возможная причина: null в параметре d.

 1: class Formatter < 2: public String format(String value) < 3: return "["+value+"]"; 4: >5: > 6: 7: public class TestNPE < 8: public static String handle(Formatter f, String s) < 9: if(s.isEmpty()) < 10: return "(none)"; 11: >12: return f.format(s.trim()); 13: > 14: >
Exception in thread "main" java.lang.NullPointerException at TestNPE.handle(TestNPE.java:12)

Теперь метод format нестатический, и f вполне может быть источником ошибки. Зато s не может быть ни под каким соусом: в девятой строке уже было обращение к s. Если бы s было null, исключение бы случилось в девятой строке. Просмотр логики кода перед исключением довольно часто помогает отбросить некоторые варианты.

С логикой, конечно, надо быть внимательным. Предположим, условие в девятой строчке было бы написано так:

Теперь в самой строчке обращения к полям и методам s нету, а метод equals корректно обрабатывает null, возвращая false, поэтому в таком случае ошибку в двенадцатой строке мог вызвать как f, так и s. Анализируя вышестоящий код, уточняйте в документации или исходниках, как используемые методы и конструкции реагируют на null. Оператор конкатенации строк +, к примеру, никогда не вызывает NPE.

Вот такой код (здесь может играть роль версия Java, я использую Oracle JDK 1.7.0.45):

 1: import java.io.PrintWriter; 2: 3: public class TestNPE < 4: public static void dump(PrintWriter pw, MyObject obj) < 5: pw.print(obj); 6: >7: >
Exception in thread "main" java.lang.NullPointerException at java.io.PrintWriter.write(PrintWriter.java:473) at java.io.PrintWriter.print(PrintWriter.java:617) at TestNPE.dump(TestNPE.java:5)

В параметре pw не может быть null, иначе нам не удалось бы войти в метод print. Возможно, null в obj? Легко проверить, что pw.print(null) выводит строку «null» без всяких исключений. Пойдём с конца. Исключение случилось здесь:

472: public void write(String s)

В строке 473 возможна только одна причина NPE: обращение к методу length строки s. Значит, s содержит null. Как так могло получиться? Поднимемся по стеку выше:

616: public void print(Object obj)

В метод write передаётся результат вызова метода String.valueOf. В каком случае он может вернуть null?

public static String valueOf(Object obj)

Единственный возможный вариант — obj не null, но obj.toString() вернул null. Значит, ошибку надо искать в переопределённом методе toString() нашего объекта MyObject. Заметьте, в stack trace MyObject вообще не фигурировал, но проблема именно там. Такой несложный анализ может сэкономить кучу времени на попытки воспроизвести ситуацию в отладчике.

Не стоит забывать и про коварный автобоксинг. Пусть у нас такой код:

Exception in thread "main" java.lang.NullPointerException at TestNPE.getCount(TestNPE.java:3)

На первый взгляд единственный вариант — это null в параметре obj. Но следует взглянуть на класс MyContainer:

import java.util.List; public class MyContainer < Listelements; public MyContainer(List elements) < this.elements = elements; >public Integer getCount() < return elements == null ? null : elements.size(); >>

Мы видим, что getCount() возвращает Integer, который автоматически превращается в int именно в третьей строке TestNPE.java, а значит, если getCount() вернул null, произойдёт именно такое исключение, которое мы видим. Обнаружив класс, подобный классу MyContainer, посмотрите в истории системы контроля версий, кто его автор, и насыпьте ему крошек под одеяло.

Помните, что если метод принимает параметр int, а вы передаёте Integer null, то анбоксинг случится до вызова метода, поэтому NPE будет указывать на строку с вызовом.

В заключение хочется пожелать пореже запускать отладчик: после некоторой тренировки анализ кода в голове нередко выполняется быстрее, чем воспроизведение трудноуловимой ситуации.

Источник

Multiple ways to fix java.util.NoSuchElementException: No value present error in java

In this tutorial, Learn how to fix java.util.NoSuchElementException: No value present error in java application.

This error java.util.NoSuchElementException: No value present thrown when there is no element found in Optional object with Stream API in java8.

Let’s create an array and initialize it with string values. You can check how to create and initialize an array in a single line

Let’s see a simple example to check if a string exists in an array.

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Test  public static void main(String[] args)  ListString> srs = new ArrayList<>(Arrays.asList("One", "two", "three")); String str=srs.stream().filter(e->e.equals("ten")).findFirst().get(); > >

It throws an error Exception in thread “main” java.util.NoSuchElementException: No value present

Exception in thread "main" java.util.NoSuchElementException: No value present at java.util.Optional.get(Optional.java:135) at Test.main(Test.java:8)
  • Iterated an array using stream API in java8, Stream is another way to iterate the enumerated object to improve performance
  • It returns the Stream object using the stream() method
  • Calling filter method on stream which matched with a given predicate for each element and returns matched values with stream
  • Calling the first element using findFirst from the matched stream and returns Optional class
  • if optional Object is empty, get method return no value present error i.e Optional.get() method gives java.util.NoSuchElementException when Optional object is empty

Here is a get method implemented in java8

 public T get()  if (value == null)  throw new NoSuchElementException("No value present"); > return value; >

There are multiple ways we can fix to check for the optional object is empty or not.

Let’s see some other simple examples to reproduce and solution for this error

OptionalInteger> number1 = Optional.of(123); OptionalInteger> number2 = Optional.empty(); System.out.println(number1.get()); // 123 System.out.println(number2.get()); // Exception in thread "main" java.util.NoSuchElementException: No value present

We can check Optional empty or not using isPresent() method in Optional class

 if (number2.isPresent()) System.out.println(number2.get()); >else System.out.println("number2 is an empty"); >

isPresent() method returns true if value exists, else return false .

Thus, we can avoid an error.

Another way using the orElse method

The orElse method returns the default value assigned with an argument if optional is empty. otherwise, the returns value is present in the Optional class.

OptionalInteger> number1 = Optional.of(123); System.out.println(number1.orElse(0)); // 123 OptionalInteger> number2 = Optional.empty(); System.out.println(number2.orElse(0));

Finally, you can use the orElseThrow method.

Sometimes we want to throw an error if Optional is empty, It is handy and helpful.

 OptionalInteger> number1 = Optional.of(123); System.out.println(number1.orElse(0)); // 123 OptionalInteger> number2 = Optional.empty(); System.out.println(number2.orElseThrow(Exception::new));

We can use either orElse with the default value orElseThrow method.

How to fix NoSuchElement error in java8 streams

Here is a complete example to avoid errors in the java8 stream.

It usually occurs during the streaming process with map , filter etc. methods.

We have to use orElse returns assigned default value else the return value exists in the Optional class.

import java.util.List; import java.util.Optional; public class Test  public static void main(String[] args) throws Exception ListString> srs = new ArrayList<>(Arrays.asList("one", "two", "three")); String result=srs.stream().filter(e->e.equals("ten")).findFirst().orElse(""); System.out.println(result); String result1=srs.stream().filter(e->e.equals("one")).findFirst().orElse(""); System.out.println(result1); > > You learned multiple ways to fix java.util.NoSuchElementException: No value present error in java8 streams.

Источник

Оцените статью