Error executing task on server java lang nullpointerexception null

В статье описано, что за ошибка java.lang.nullpointerexception, какие причины её вызывают, и как устранить её на вашем ПК.

Ряд пользователей (да и разработчиков) программных продуктов на языке Java могут столкнуться с ошибкой java.lang.nullpointerexception (сокращённо NPE), при возникновении которой запущенная программа прекращает свою работу. Обычно это связано с некорректно написанным телом какой-либо программы на Java, требуя от разработчиков соответствующих действий для исправления проблемы. В этом материале я расскажу, что это за ошибка, какова её специфика, а также поясню, как исправить ошибку java.lang.nullpointerexception.

Ошибка java.lang.nullpointerexception

Содержание

  1. Что это за ошибка java.lang.nullpointerexception
  2. Как исправить ошибку java.lang.nullpointerexception
  3. Для пользователей
  4. Для разработчиков
  5. Заключение

Что это за ошибка java.lang.nullpointerexception

Появление данной ошибки знаменует собой ситуацию, при которой разработчик программы пытается вызвать метод по нулевой ссылке на объект. В тексте сообщения об ошибке система обычно указывает stack trace и номер строки, в которой возникла ошибка, по которым проблему будет легко отследить.

Номер строки с ошибкой

Что в отношении обычных пользователей, то появление ошибки java.lang.nullpointerexception у вас на ПК сигнализирует, что у вас что-то не так с функционалом пакетом Java на вашем компьютере, или что программа (или онлайн-приложение), работающие на Java, функционируют не совсем корректно. Если у вас возникает проблема, при которой Java апплет не загружен, рекомендую изучить материал по ссылке.

Скриншот ошибки Java

Как исправить ошибку java.lang.nullpointerexception

Как избавиться от ошибки java.lang.nullpointerexception? Способы борьбы с проблемой можно разделить на две основные группы – для пользователей и для разработчиков.

Для пользователей

Если вы встретились с данной ошибкой во время запуска (или работы) какой-либо программы (особенно это касается minecraft), то рекомендую выполнить следующее:

  1. Переустановите пакет Java на своём компьютере. Скачать пакет можно, к примеру, вот отсюда;
  2. Переустановите саму проблемную программу (или удалите проблемное обновление, если ошибка начала появляться после такового);
  3. Напишите письмо в техническую поддержку программы (или ресурса) с подробным описанием проблемы и ждите ответа, возможно, разработчики скоро пофиксят баг.
  4. Также, в случае проблем в работе игры Майнкрафт, некоторым пользователям помогло создание новой учётной записи с административными правами, и запуск игры от её имени.Картинка Minecraft

Для разработчиков

Разработчикам стоит обратить внимание на следующее:

  1. Вызывайте методы equals(), а также equalsIgnoreCase() в известной строке литерала, и избегайте вызова данных методов у неизвестного объекта;
  2. Вместо toString() используйте valueOf() в ситуации, когда результат равнозначен;
  3. Применяйте null-безопасные библиотеки и методы;
  4. Старайтесь избегать возвращения null из метода, лучше возвращайте пустую коллекцию;
  5. Применяйте аннотации @Nullable и @NotNull;
  6. Не нужно лишней автоупаковки и автораспаковки в создаваемом вами коде, что приводит к созданию ненужных временных объектов;
  7. Регламентируйте границы на уровне СУБД;
  8. Правильно объявляйте соглашения о кодировании и выполняйте их.Картинка об ошибке java.lang.nullpointerexception

Заключение

При устранении ошибки java.lang.nullpointerexception важно понимать, что данная проблема имеет программную основу, и мало коррелирует с ошибками ПК у обычного пользователя. В большинстве случаев необходимо непосредственное вмешательство разработчиков, способное исправить возникшую проблему и наладить работу программного продукта (или ресурса, на котором запущен сам продукт). В случае же, если ошибка возникла у обычного пользователя (довольно часто касается сбоев в работе игры Minecraft), рекомендуется установить свежий пакет Java на ПК, а также переустановить проблемную программу.

Опубликовано 21.02.2017 Обновлено 03.09.2022

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying «no object».

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled «HERE» is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception … but the standard javac compiler doesn’t.)

Second observation: when I run the program, it outputs two lines of «gobbledy-gook». WRONG!! That’s not gobbledy-gook. It is a stacktrace … and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let’s look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be «main». Let’s move on …
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • «at Test.main» says that we were in the main method of the Test class.
  • «Test.java:4» gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the «HERE» comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first «at» line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 — Not quite true. There are things called nested exceptions…

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let’s illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and… BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first «at» line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second «at» line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let’s try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two «at» lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null … but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo … so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

В этом посте я покажу наглядный пример того, как исправить ошибку исключения Null Pointer (java.lang.nullpointerexception). В Java особое значение null может быть назначено для ссылки на объект и означает, что объект в данный момент указывает неизвестную область данных.

NullPointerException появляется, если программа обращается или получает доступ к объекту, а ссылка на него равна нулю (null).

Это исключение возникает следующих случаях:

  • Вызов метода из объекта значения null.
  • Доступ или изменение объекта поля null.
  • Принимает длину null(если бы это был массив Java).
  • Доступ или изменение ячеек объекта null.
  • Показывает «0», значение Throwable.
  • При попытке синхронизации по нулевому объекту.

NullPointerException является RuntimeException, и, таким образом, компилятор Javac не заставляет вас использовать блок try-catch для соответствующей обработки.

ошибка error java lang nullpointerexception

Зачем нам нужно значение null?

Как уже упоминалось, null – это специальное значение, используемое в Java. Это чрезвычайно полезно при кодировании некоторых шаблонов проектирования, таких как Null Object pattern и шаблон Singleton pattern.

Шаблон Singleton обеспечивает создание только одного экземпляра класса, а также направлен на предоставление глобального доступа к объекту.

Например, простой способ создания не более одного экземпляра класса – объявить все его конструкторы как частные, а затем создать открытый метод, который возвращает уникальный экземпляр класса:

import java.util.UUID;

class Singleton {

     private static Singleton single = null;
     private String ID = null;

     private Singleton() {
          /* Make it private, in order to prevent the creation of new instances of
           * the Singleton class. */

          ID = UUID.randomUUID().toString(); // Create a random ID.
     }

     public static Singleton getInstance() {
          if (single == null)
               single = new Singleton();

          return single;
     }

     public String getID() {
          return this.ID;
     }
}

public class TestSingleton {
     public static void main(String[] args) {
          Singleton s = Singleton.getInstance();
          System.out.println(s.getID());
     }
}

В этом примере мы объявляем статический экземпляр класса Singleton. Этот экземпляр инициализируется не более одного раза внутри метода getInstance.

Обратите внимание на использование нулевого значения, которое разрешает создание уникального экземпляра.

Как избежать исключения Null Pointer

Чтобы решить и избежать исключения NullPointerException, убедитесь, что все ваши объекты инициализированы должным образом, прежде чем использовать их.

Когда вы объявляете ссылочную переменную, вы должны создать указатель на объект и убедиться, что указатель не является нулевым, прежде чем запрашивать метод или поле у ​​объекта.

Кроме того, если выдается исключение, используйте информацию, находящуюся в трассировке стека исключения. Трассировка стека выполнения обеспечивается JVM, чтобы включить отладку. Найдите метод и строку, в которой было обнаружено исключение, а затем выясните, какая ссылка равна нулю в этой конкретной строке.

Опишем некоторые методы, которые имеют дело с вышеупомянутым исключением. Однако они не устраняют проблему, и программист всегда должен быть осторожен.

  1. Сравнение строк с литералами

Очень распространенный случай, выполнения программы включает сравнение между строковой переменной и литералом. Литерал может быть строкой или элементом Enum.

Вместо того, чтобы вызывать метод из нулевого объекта, рассмотрите возможность вызова его из литерала. Например:

String str = null;
if(str.equals("Test")) {
     /* The code here will not be reached, as an exception will be thrown. */
}

Приведенный выше фрагмент кода вызовет исключение NullPointerException. Однако, если мы вызываем метод из литерала, поток выполнения продолжается нормально:

String str = null;
if("Test".equals(str)) {
     /* Correct use case. No exception will be thrown. */
}
  1. Проверка аргументов метода

Перед выполнением вашего собственного метода обязательно проверьте его аргументы на наличие нулевых значений.

В противном случае вы можете вызвать исключение IllegalArgumentException.

Например:

public static int getLength(String s) {
     if (s == null)
          throw new IllegalArgumentException("The argument cannot be null");

     return s.length();
}
  1. Предпочтение метода String.valueOf() вместо of toString()

Когда код вашей программы требует строковое представление объекта, избегайте использования метода toString объекта. Если ссылка вашего объекта равна нулю, генерируется исключение NullPointerException.

Вместо этого рассмотрите возможность использования статического метода String.valueOf, который не выдает никаких исключений и «ноль», если аргумент функции равен нулю.

  1. Используйте Ternary Operator

Ternary Operator – может быть очень полезным. Оператор имеет вид:

boolean expression ? value1 : value2;

Сначала вычисляется логическое выражение. Если выражение true, то возвращается значение1, в противном случае возвращается значение2. Мы можем использовать Ternary Operator для обработки нулевых указателей следующим образом:

String message = (str == null) ? "" : str.substring(0, 10);

Переменная message будет пустой, если ссылка str равна нулю. В противном случае, если str указывает на фактические данные, в сообщении будут первые 10 символов.

  1. создайте методы, которые возвращают пустые коллекции вместо нуля.

Очень хорошая техника – создавать методы, которые возвращают пустую коллекцию вместо нулевого значения. Код вашего приложения может перебирать пустую коллекцию и использовать ее методы и поля. Например:

public class Example {
     private static List<Integer> numbers = null;

     public static List<Integer> getList() {
          if (numbers == null)
               return Collections.emptyList();
          else
               return numbers;
     }
}
  1. Воспользуйтесь классом Apache’s StringUtils.

Apache’s Commons Lang – это библиотека, которая предоставляет вспомогательные утилиты для API java.lang, такие как методы манипулирования строками.

Примером класса, который обеспечивает манипулирование String, является StringUtils.java, который спокойно обрабатывает входные строки с нулевым значением.

Вы можете воспользоваться методами: StringUtils.isNotEmpty, StringUtils.IsEmpty и StringUtils.equalsчтобы избежать NullPointerException. Например:

if (StringUtils.isNotEmpty(str)) {
     System.out.println(str.toString());
}
  1. Используйте методы: contains(), containsKey(), containsValue()

Если в коде вашего приложения используется Maps, рассмотрите возможность использования методов contains, containsKey и containsValue. Например, получить значение определенного ключа после того, как вы проверили его существование на карте:

Map<String, String> map = …
…
String key = …
String value = map.get(key);
System.out.println(value.toString()); // An exception will be thrown, if the value is null.

System.out.println(value.toString()); // В приведенном выше фрагменте мы не проверяем, существует ли на самом деле ключ внутри карты, и поэтому возвращаемое значение может быть нулевым. Самый безопасный способ следующий:

Map<String, String> map = …
…
String key = …
if(map.containsKey(key)) {
     String value = map.get(key);
     System.out.println(value.toString()); // No exception will be thrown.
}
  1. Проверьте возвращаемое значение внешних методов

На практике очень часто используются внешние библиотеки. Эти библиотеки содержат методы, которые возвращают ссылку. Убедитесь, что возвращаемая ссылка не пуста.

  1. Используйте Утверждения

Утверждения очень полезны при тестировании вашего кода и могут использоваться, чтобы избежать выполнения фрагментов кода. Утверждения Java реализуются с помощью ключевого слова assert и выдают AssertionError.

Обратите внимание, что вы должны включить флажок подтверждения JVM, выполнив его с аргументом -ea. В противном случае утверждения будут полностью проигнорированы.

Примером использования утверждений Java является такая версия кода:

public static int getLength(String s) {
     /* Ensure that the String is not null. */
     assert (s != null);

     return s.length();
}

Если вы выполните приведенный выше фрагмент кода и передадите пустой аргумент getLength, появится следующее сообщение об ошибке:
Exception in thread "main" java.lang.AssertionError
Также вы можете использовать класс Assert предоставленный средой тестирования jUnit.

  1. Модульные тесты

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

Существующие безопасные методы NullPointerException

Доступ к статическим членам или методам класса

Когда ваш вы пытаетесь получить доступ к статической переменной или методу класса, даже если ссылка на объект равна нулю, JVM не выдает исключение.

Это связано с тем, что компилятор Java хранит статические методы и поля в специальном месте во время процедуры компиляции. Статические поля и методы связаны не с объектами, а с именем класса.

class SampleClass {

     public static void printMessage() {
          System.out.println("Hello from Java Code Geeks!");
     }
}

public class TestStatic {
     public static void main(String[] args) {
          SampleClass sc = null;
          sc.printMessage();
     }
}

Несмотря на тот факт, что экземпляр SampleClass равен нулю, метод будет выполнен правильно. Однако, когда речь идет о статических методах или полях, лучше обращаться к ним статическим способом, например, SampleClass.printMessage ().

Оператор instanceof

Оператор instanceof может использоваться, даже если ссылка на объект равна нулю.

Оператор instanceof возвращает false, когда ссылка равна нулю.

String str = null;
if(str instanceof String)
     System.out.println("It's an instance of the String class!");
else
     System.out.println("Not an instance of the String class!");

В результате, как и ожидалось:

Not an instance of the String class!

Смотрите видео, чтобы стало понятнее.



Содержание

  1. java.util.concurrent.ExecutionException: java.lang.NullPointerException #2464
  2. Comments
  3. Fatal error in 7.1.6 recommended build #2803
  4. Comments
  5. Crash on server when getting into a vehicle #593
  6. Comments
  7. 1.11.2 — [Server thread/FATAL]: Error executing task java.util.concurrent.ExecutionException: java.lang.NullPointerException #28
  8. Comments
  9. Minecraft Forums
  10. I need help

java.util.concurrent.ExecutionException: java.lang.NullPointerException #2464

I am currently running

  • SpongeForge version: 3472
  • Forge version: 2705
  • Java version: 1,8
  • Operating System: Ubuntu 16.04

java.util.concurrent.ExecutionException: java.lang.NullPointerException
at java.util.concurrent.FutureTask.report(FutureTask.java:122)

[?:1.8.0_181]
at java.util.concurrent.FutureTask.get(FutureTask.java:192)

[?:1.8.0_181]
at net.minecraft.util.Util.func_181617_a(SourceFile:47) [h.class:?]
at org.spongepowered.common.SpongeImplHooks.onUtilRunTask(SpongeImplHooks.java:294) [SpongeImplHooks.class:1.12.2-2705-7.1.0-BETA-3472
at net.minecraft.server.MinecraftServer.redirect$onRun$zjk000(MinecraftServer.java:3970) [MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.func_71190_q(MinecraftServer.java:723) [MinecraftServer.class:?]
at net.minecraft.server.dedicated.DedicatedServer.func_71190_q(DedicatedServer.java:396) [nz.class:?]
at net.minecraft.server.MinecraftServer.func_71217_p(MinecraftServer.java:668) [MinecraftServer.class:?]
at net.minecraft.server.MinecraftServer.run(MinecraftServer.java:526) [MinecraftServer.class:?]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_181]
Caused by: java.lang.NullPointerException
at com.ebkr.expansiveenergy.items.ItemExpansiveWrench.func_180614_a(ItemExpansiveWrench.java:34)

[ItemExpansiveWrench.class:?]
at net.minecraft.item.ItemStack.func_179546_a(ItemStack.java:2965)

[aip.class:?]
at net.minecraft.server.management.PlayerInteractionManager.func_187251_a(PlayerInteractionManager.java:1326)

[or.class:?]
at net.minecraft.network.NetHandlerPlayServer.redirect$onProcessRightClickBlock$zio000(NetHandlerPlayServer.java:2415)

[pa.class:?]
at net.minecraft.network.NetHandlerPlayServer.func_184337_a(NetHandlerPlayServer.java:739)

[pa.class:?] ehind, skipping 47 ti
at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.func_148833_a(SourceFile:55)

[ma.class:?]
at net.minecraft.network.play.client.CPacketPlayerTryUseItemOnBlock.func_148833_a(SourceFile:11)

[ma.class:?]
at org.spongepowered.common.event.tracking.phase.packet.PacketPhaseUtil.onProcessPacket(PacketPhaseUtil.java:193)

[PacketPhaseUtil.cl
at net.minecraft.network.PacketThreadUtil$1.redirect$onProcessPacket$zlg000(SourceFile:539)

[hv$1.class:?]
at net.minecraft.network.PacketThreadUtil$1.run(SourceFile:13)

[hv$1.class:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)

[?:1.8.0_181]
at java.util.concurrent.FutureTask.run(FutureTask.java:266)

[?:1.8.0_181]
at net.minecraft.util.Util.func_181617_a(SourceFile:46)

The text was updated successfully, but these errors were encountered:

Источник

Fatal error in 7.1.6 recommended build #2803

  • SpongeForge version: 1.12.2-2825-7.1.6
  • Forge version: 1.12.2 — 14.23.5.2838
  • Java version: Version 8 Update 211 build 1.8.0_211-b12
  • Operating System: Windows Server 2012 x64

The text was updated successfully, but these errors were encountered:

Going to need a bit more information — specifically the stack trace below Caused by: java.lang.NullPointerException . If you have the full debug.log , that would help.

Going to need a bit more information — specifically the stack trace below Caused by: java.lang.NullPointerException . If you have the full debug.log , that would help.

It looks like something is swallowing the NPE trace. This is outside of Sponge’s code at this point.

Try the following to triage:

  • Pull SF from your server and see if it still happens
  • If it does not happen then re-add SF and remove mods 1 by 1 until we can find who is in-compatible
  • If it does happen then remove SF and remove mods 1 by 1 until we can find who is causing it.

Unless someone else has encountered this and knows who is at fault.

I updated the Mekanism mod and then found this error.

It looks like something is swallowing the NPE trace. This is outside of Sponge’s code at this point.

Try the following to triage:

  • Pull SF from your server and see if it still happens
  • If it does not happen then re-add SF and remove mods 1 by 1 until we can find who is in-compatible
  • If it does happen then remove SF and remove mods 1 by 1 until we can find who is causing it.

Unless someone else has encountered this and knows who is at fault.

I updated the Mekanism mod and then found this error. Today I have problem with ImmersiveEngineering mod. i created report in his repository BluSunrize/ImmersiveEngineering#3484

Mekanism devolpmers say:

Unless you can get a proper stack trace from it, there’s nothing we can do. IMO not even enough to pin it on Mekanism, even if it was the only mod you updated.

It’s quite odd that the caused by trace has no stacktrace attached. Definitely not caused by us.

My English is bad and very difficult to communicate.
mekanism/Mekanism#5504

@mistek131995 Then you’ll need to do triage based on the steps I gave above and come back when you know more.

I’ve posted on their issue page, a relavant stacktrace was towards the top of the debug log. It seems to me that they are trying to put a null into a EnumMap — but it’s unclear where that null came from and could be symptomatic of something else see #2802 (comment) as to when this could be null .

@mistek131995 I advise you still do what @Zidane suggests, because we can then determine if something is going wrong on our end too. In particular, try removing SpongeForge and try again, do you still get these traces?

Я разместил на странице их проблемы соответствующую трассировку стека в верхней части журнала отладки. Мне кажется , что они пытаются положить null в EnumMap — но непонятно , откуда что null пришли и может быть симптомом чего — то другого.

@ mistek131995 Я советую вам по-прежнему делать то, что предлагает @Zidane , потому что тогда мы можем определить, идет ли что-то не так и с нашей стороны. В частности, попробуйте удалить SpongeForge и попробуйте еще раз, вы все еще получаете эти следы?

I setup old mod and SpongeForge version and watching the console. Now there are no errors.

Closing as the Mekanism devs have been alerted to a stack of the issue and I believe will be pushing a fix on their ends.

Источник

Crash on server when getting into a vehicle #593

When entering a vehicle, a server-side crash occurs with the following error:

[20:50:26] [Client thread/FATAL] [minecraft/Minecraft]: Error executing task java.util.concurrent.ExecutionException: java.lang.NullPointerException at java.util.concurrent.FutureTask.report(Unknown Source)

[?:1.8.0_271] at java.util.concurrent.FutureTask.get(Unknown Source)

[?:1.8.0_271] at net.minecraft.util.Util.func_181617_a(Util.java:48) [h.class:?] at net.minecraft.client.Minecraft.func_71411_J(Minecraft.java:1088) [bib.class:?] at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:398) [bib.class:?] at net.minecraft.client.main.Main.main(SourceFile:123) [Main.class:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

[?:1.8.0_271] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

[?:1.8.0_271] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

[?:1.8.0_271] at java.lang.reflect.Method.invoke(Unknown Source)

[?:1.8.0_271] at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) [launchwrapper-1.12.jar:?] at net.minecraft.launchwrapper.Launch.main(Launch.java:28) [launchwrapper-1.12.jar:?] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

[?:1.8.0_271] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

[?:1.8.0_271] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

[?:1.8.0_271] at java.lang.reflect.Method.invoke(Unknown Source)

[?:1.8.0_271] at org.multimc.onesix.OneSixLauncher.launchWithMainClass(OneSixLauncher.java:196) [NewLaunch.jar:?] at org.multimc.onesix.OneSixLauncher.launch(OneSixLauncher.java:231) [NewLaunch.jar:?] at org.multimc.EntryPoint.listen(EntryPoint.java:143) [NewLaunch.jar:?] at org.multimc.EntryPoint.main(EntryPoint.java:34) [NewLaunch.jar:?] Caused by: java.lang.NullPointerException at minecrafttransportsimulator.packets.components.APacketEntity.handle(APacketEntity.java:36)

[APacketEntity.class:?] at mcinterface1122.InterfaceNetwork$WrapperHandler$1.run(InterfaceNetwork.java:146)

[InterfaceNetwork$WrapperHandler$1.class:?] at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)

[?:1.8.0_271] at java.util.concurrent.FutureTask.run(Unknown Source)

[?:1.8.0_271] at net.minecraft.util.Util.func_181617_a(Util.java:47)

[h.class:?] . 17 more

This error keeps outputting several hundred times. On restarting, I am in the vehicle and everything seems to work normal. When I get out and try to get in again, the same problem occurs. I noticed before the crash that in the chat the following output is given:

[20:47:26] [Client thread/INFO] [minecraft/GuiNewChat]: [CHAT] IMMERSIVE VEHICLES ERROR: Tried to play a sound, but was told no sound slots were available. Some mod is taking up all the sound slots. Probabaly Immersive Railroading. Sound will not play.

Edit: needed to put it in a ZIP file, it was too large. There was no crash report, but the server just stopped as seen in the debug log I attached.

The text was updated successfully, but these errors were encountered:

Источник

1.11.2 — [Server thread/FATAL]: Error executing task java.util.concurrent.ExecutionException: java.lang.NullPointerException #28

Players were unable to open chests or click on crafting tables, I checked the console and found this.

Removing the mod fixed the issue.

The text was updated successfully, but these errors were encountered:

Guarantee that this is nothing to do with me. Need a little more info if there is going to be any chance of tracking this down. Looking at the console excerpts you have some very ‘rough’ mods in there as there appears to be a bunch of stdout ‘logging’ in there for simple forge events. Concurrent Execution Exception basically means you have another thread touching the same stuff that Morpheus is at the same time. If I had to guess I’d say you are running a sponge server which is not something I can support unfortunately, at least not without a proper log, I need more info about the environment this happens in instead of just trying to guess about it.

I am not running a sponge server for this pack(because its in testing) specifically so I don’t get the «its sponge not us».

forge-1.11.2-13.20.0.2223-universal — only. no sponge. This is upgraded from the pack default so we could add your mod.

Can’t even begin to track down which mod is causing the problem from that info, sorry. My only advice for tracking this down would be to start removing mods that you think could be clashing with Morpheus until you find the culprit. I’m closing this issue though as I’m satisfied that the problem isn’t in my code based on the limited information you’ve given me. I’m happy to reopen should that not be the case.

Источник

Minecraft Forums

I need help

I load into a server then crash every single time, I get fatal errors from launch report thing.

  • Out of the Water
  • Join Date: 1/13/2019
  • Posts: 7
  • Member Details

  • Enderdragon Slayer
  • Join Date: 11/20/2012
  • Posts: 14,806
  • Member Details

Post the entire log, use paste.ubuntu.com.

  • Out of the Water
  • Join Date: 1/13/2019
  • Posts: 7
  • Member Details

don’t know if that’s what you wanted let me know

  • Out of the Water
  • Join Date: 1/13/2019
  • Posts: 7
  • Member Details

  • Enderdragon Slayer
  • Join Date: 11/20/2012
  • Posts: 14,806
  • Member Details

An error report file with more information is saved as:

Источник

Ошибка java.lang.nullpointerexception может возникать во время запуска или работы приложений, созданных на Java. С ошибкой сталкиваются как обычные пользователи, так и опытные разработчики на этом языке программирования. В сегодняшней статье мы рассмотрим с вами решение ошибки java.lang.nullpointerexception.

Решение ошибки

java.lang.nullpointerexception

Причин у этой ошибки как правило две: некорректно работающая программа и проблемы с работой пакета Java, который установлен на компьютере пользователя. Чтобы устранить ошибку java.lang.nullpointerexception, выполняют следующие несколько шагов:

  • Попробуйте переустановить Java-пакет, установленный в вашей операционной системе. Зайдите в «Программы и компоненты» и удалите установленный пакет. Затем перейдите по этой ссылке на официальный сайт, загрузите последнюю версию Java и установите ее.
  • Помимо прочего, сама запускаемая программа может быть источником проблемы. Возможно, что-то не так пошло во время установочного процесса, вследствие чего были повреждены файлы программы. В общем, переустановите и посмотрите на результат.
  • Если вы пытаетесь запустить у себя на компьютере Minecraft и сталкивайтесь с ошибкой, то многим пользователям помогло создание в системе новой Администраторской учетной записи, а затем запуск игры от имени Администратора(звучит сложнее, чем кажется).
  • Если вы можете связаться с разработчиками запускаемой программы – сделайте это и объясните им ситуацию с ошибкой java.lang.nullpointerexception.

Обычно, вышеуказанные решения помогают большинству пользователей избавиться от ошибки java.lang.nullpointerexception. Мы надеемся, что и они вам помогли.

Довольно часто при разработке на Java программисты сталкиваются с NullPointerException, появляющимся в самых неожиданных местах. В этой статье мы разберёмся, как это исправить и как стараться избегать появления NPE в будущем.

NullPointerException (оно же NPE) это исключение, которое выбрасывается каждый раз, когда вы обращаетесь к методу или полю объекта по ссылке, которая равна null. Разберём простой пример:

Integer n1 = null;
System.out.println(n1.toString());

Здесь на первой строке мы объявили переменную типа Integer и присвоили ей значение null (то есть переменная не указывает ни на какой существующий объект).
На второй строке мы обращаемся к методу toString переменной n1. Так как переменная равна null, метод не может выполниться (переменная не указывает ни на какой реальный объект), генерируется исключение NullPointerException:

Exception in thread "main" java.lang.NullPointerException
	at ru.javalessons.errors.NPEExample.main(NPEExample.java:6)

Как исправить NullPointerException

В нашем простейшем примере мы можем исправить NPE, присвоив переменной n1 какой-либо объект (то есть не null):

Integer n1 = 16;
System.out.println(n1.toString());

Теперь не будет исключения при доступе к методу toString и наша программа отработает корректно.

Если ваша программа упала из-за исключение NullPointerException (или вы перехватили его где-либо), вам нужно определить по стектрейсу, какая строка исходного кода стала причиной появления этого исключения. Иногда причина локализуется и исправляется очень быстро, в нетривиальных случаях вам нужно определять, где ранее по коду присваивается значение null.

Иногда вам требуется использовать отладку и пошагово проходить программу, чтобы определить источник NPE.

Как избегать исключения NullPointerException

Существует множество техник и инструментов для того, чтобы избегать появления NullPointerException. Рассмотрим наиболее популярные из них.

Проверяйте на null все объекты, которые создаются не вами

Если объект создаётся не вами, иногда его стоит проверять на null, чтобы избегать ситуаций с NullPinterException. Здесь главное определить для себя рамки, в которых объект считается «корректным» и ещё «некорректным» (то есть невалидированным).

Не верьте входящим данным

Если вы получаете на вход данные из чужого источника (ответ из какого-то внешнего сервиса, чтение из файла, ввод данных пользователем), не верьте этим данным. Этот принцип применяется более широко, чем просто выявление ошибок NPE, но выявлять NPE на этом этапе можно и нужно. Проверяйте объекты на null. В более широком смысле проверяйте данные на корректность, и консистентность.

Возвращайте существующие объекты, а не null

Если вы создаёте метод, который возвращает коллекцию объектов – не возвращайте null, возвращайте пустую коллекцию. Если вы возвращаете один объект – иногда удобно пользоваться классом Optional (появился в Java 8).

Заключение

В этой статье мы рассказали, как исправлять ситуации с NullPointerException и как эффективно предотвращать такие ситуации при разработке программ.

Время прочтения
5 мин

Просмотры 265K

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

Итак, вы узнали, что ваше приложение упало с NPE, и у вас есть только stack trace. Возможно, вам прислал его клиент, или вы сами увидели его в логах. Давайте посмотрим, какие выводы из него можно сделать.

NPE может произойти в трёх случаях:

  1. Его кинули с помощью throw
  2. Кто-то кинул null с помощью throw
  3. Кто-то пытается обратиться по null-ссылке

Во втором и третьем случае message в объекте исключения всегда null, в первом может быть произвольным. К примеру, java.lang.System.setProperty кидает NPE с сообщением «key can’t be null», если вы передали в качестве key null. Если вы каждый входной параметр своих методов проверяете таким же образом и кидаете исключение с понятным сообщением, то вам остаток этой статьи не потребуется.

Обращение по null-ссылке может произойти в следующих случаях:

  1. Вызов нестатического метода класса
  2. Обращение (чтение или запись) к нестатическому полю
  3. Обращение (чтение или запись) к элементу массива
  4. Чтение length у массива
  5. Неявный вызов метода valueOf при анбоксинге (unboxing)

Важно понимать, что эти случаи должны произойти именно в той строчке, на которой заканчивается stack trace, а не где-либо ещё.

Рассмотрим такой код:

 1: class Data {
 2:    private String val;
 3:    public Data(String val) {this.val = val;}
 4:    public String getValue() {return val;}
 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: }

Откуда-то был вызван метод handle с какими-то параметрами, и вы получили:

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: }

Снова вызываем метод handle и получаем

Exception in thread "main" java.lang.NullPointerException
	at TestNPE.handle(TestNPE.java:12)

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

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

if("".equals(s))

Теперь в самой строчке обращения к полям и методам 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: }

Вызываем метод dump, получаем такое исключение:

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:     write(s, 0, s.length());
474: }

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

616: public void print(Object obj) {
617:     write(String.valueOf(obj));
618: }

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

public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

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

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

 1: public class TestNPE {
 2:     public static int getCount(MyContainer obj) {
 3:         return obj.getCount();
 4:     }
 5: }

И такое исключение:

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

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

import java.util.List;

public class MyContainer {
    List<String> elements;
    
    public MyContainer(List<String> 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 будет указывать на строку с вызовом.

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

You must have come across something called a NullPointerException if you have worked on Java-based applications. The Null Pointer Exception is one of the most common errors in Java application development. This exception is usually the result of a human error, buttime can get wasted on debugging errors like this one. This issue is not entirely a syntactical error, so it can get tricky to identify the problem at times.

In this article, we take a look at what java.lang.NullPointerException is, why does it happen, how you can fix it, and some of the best practices to follow to avoid running into wild null pointers. Without further ado, let’s begin.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

What is java.lang.NullPointerException?

The Null Pointer Exception is one of the several Exceptions supported by the Java language. This indicates that an attempt has been made to access a reference variable that currently points to null.

Null is the default value in Java assigned to the variables which are not initialized by the user after or with a declaration. Consider the following example where you declare a variable like this:

And then try to print the contents of the variable:

System.out.println(str);
// => null

As can be seen above, ‘null’ gets printed on the output. This shows that since the variable str is uninitialized, it currently points to, or holds the value, null. The issue that a null pointing variable poses is that the variable is only a reference, and it does not point to anything. If you try to carry out some operations on the data stored in a null pointing variable, the system will not know what to do. This happens because there is no data actually stored in the variable; it points to a void entity.

Example of java.lang.NullPointer.Exception

Looking for examples of java.lang.NullPointerException is not a difficult task, as all you need to do is not initialize a variable before trying to access it. For instance, let’s consider the StringBuilder class. StringBuilder is a class that is used to handle the formation and manipulation of strings. Here’s how you would normally use the class to create strings:

import java.util.StringBuilder;

public class Test {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();

    sb.append("Hello ");
    sb.append("World!");
   
    String result = sb.toString();

    System.out.println(result);
    // => Hello World!
  }
}

If you run the above snippet, it will work just fine. Let’s take a look at its modified version that will throw a null pointer exception:

import java.util.StringBuilder;

public class Test {
  public static void main(String[] args) {
    StringBuilder sb;

    sb.append("Hello ");
    sb.append("World!");
   
    String result = sb.toString();

    System.out.println(result);
  }
}

As you can see, we did not initialize an instance of the StringBuilder class while declaring it. When the sb.append() lines are executed, sb does not point to any object in reality, rather it points to null. This is where a NullPointerException gets thrown. Due to the exception being thrown, the JVM cannot execute any statements after this.

How to Fix java.lang.NullPointerException Error

Creating a Null Pointer Exception is easy, but avoiding or fixing it is tricky. While some integrated development environments (IDEs) warn you if you are accessing a variable before initializing it with some compatible value, most IDEs can not figure this out in complex situations, such as when passing a variable through multiple method calls. The exact fix for a Null Pointer Exception depends upon your situation and code. Here are some of the top ways to fix common Null Pointer scenarios:

Check Your Code For Manual Errors

The biggest reason why Null Pointer Exceptions occur is human error. Make sure the program you have written carries the correct logic that you had initially intended. Also, run your eyes through the source code to check if you have missed out any statements, or misspelled any variables which may have led to some variable not being assigned a value.

Ensure that you have written your code the way your logic directs you to, and you have not missed out on writing any statements, or have not assigned objects to wrong references. As a rule of thumb, check that before any variable is used, it is initialized with an object.

Put Safety Checks Around Code That May Cause Null Pointer Exception

If you know the line of code that is causing your NullPointer and believe your logic is correct as well, you can wrap the section of code in a try-catch block, and define the behavior for when a Null Pointer is caught. This is how such a set-up will look like:

...
// Some code above

try {
  // Put the exception-prone code here
} catch (NullPointerException npe) {
  // Define what needs to be done when an NPE is caught
}

// Some code below
...

This happens in situations where a certain reference variable may or may not contain null. More often than not, remote API responses, device interface responses are prone to this scenario. Depending upon the availability of a result or hardware, the response variable may or may not point to an instantiated object. Using safety checks is best-suited to handle these situations.

Check For Null Before Accessing Something

This method is similar to the try-catch method. In this method, an ‘if’ block is used to check for null values before accessing a variable. Here’s how the previous snippet of code would look like if an ‘if’ block is used to catch the error:

...
// Some code above

If (myVar !== null ) {
  // Put the success logic here
} else {
  // Handle null value here
}

// Some code below
...

The biggest difference between the two methods is the scope of checks that they do. The if method checks the myVar variable only for null values, while the try-catch block catches any and all variables that are null.

This makes the ‘if’ block a more targeted and clean approach to accommodating null pointers in your application logic. However, if there is more than one variable that may be null, it is better to go with a try-catch block for simplicity.

Conclusion

This article took a look at what Null Pointer Exception is in Java, and how this error occurs. We also looked at a piece of code that will cause a Null Pointer Exception to understand how Null Pointers are created in real-life situations. Finally, we set down to identify some of the top ways to fix a Null Pointer Exception and ended our discussion by contrasting between two methods of fixing NPEs.

If you are looking to write Java programs, a Null Pointer Exception is one of the essential bugs that you must know how to fix. This exception is one of the most frequent issues and is not related to your code’s syntax or semantics. This makes the exception one of the trickiest problems to identify and fix. A quick reference for fixing the issue like this article is bound to make your experience smoother.

Понравилась статья? Поделить с друзьями:
  • Error executing task on client java lang nullpointerexception null
  • Error executing task on chunk source main thread executor for minecraft overworld
  • Error executing task java util concurrent executionexception java lang assertionerror trap
  • Error executing sql statement
  • Error executing sql script