Ошибка браузера java lang nullpointerexception

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.

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

Количество просмотров 270K

Эта простая статья скорее для начинающих разработчиков 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 будет указывать на строку с вызовом.

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

The error 500: Java.lang.nullpointerexception is an error that is faced by some developers when executing their code. Moreover, end-users also encounter the error 500 when launching an application/game or accessing a particular website. Usually, the following type of error message is shown:

Error 500 Java.Lang.NullPointerException Fix

Due to the diversity of the coding world and tools used, it is not possible to cover those in this article but for a developer, the issue is either caused by an error in the code (like calling a function before its initializing) or a server-side error (like using doPost() when doGet() was required). If that is not the case, then reinstalling IDE (as discussed later) may clear the error for a developer.

For an end-user, if the issue is not on the server-side, then the following can be considered as the main factors leading to the error 500:

  • Incompatible Browser: If a user is encountering the lang.nullpointerexception when accessing a particular website, then that browser’s incompatibility (like Edge) with that website may cause the error 500 as the website fails to call the function essential for its operations.
  • Outdated Java Version on the System: If the system’s Java version is outdated, then its incompatibility with the game, application, or website might cause the error at hand as the Java modules of the system may fail to load.
  • Interference from the System’s Firewall: If the system’s firewall is blocking the execution of Java (as a false positive), then the non-execution of the Java modules of the game, application, or website may lead to the error 500.
  • Corrupt Installation of the Game or Java: If the game or Java’s installation is corrupt, then the essential game or Java modules may fail to operate and that may result in an error message.

Try Another Browser

If a particular website is failing to load in a browser with ‘Java.lang.nullpointerexception’, then that particular browser’s incompatibility with the website could be the root cause of the error 500 as the website may fail to perform a particular operation, which may be essential for the website’s functionality. Here, trying another browser may clear the error.

  1. Download and install another browser on your device/system (if already not present).
  2. Now launch the other browser (like Chrome or Firefox) and steer to the problematic website to check if it is operating fine.
  3. If not, check if clean booting of the system (especially, any Comcast-related applications) clears the error 500.

If the issue persists, check if the problematic website can be opened on another device (preferably, using another network).

Install Java on the System

Java is available for nearly every platform like smartphones. Windows PCs, Macs, Linux distros, etc. If the problematic application/game (like Minecraft) or website requires Java on a user’s system but is not installed on that system, then that can cause the error message as Java is not available for the execution of the related modules. Here, installing Java on the user’s system may solve the problem.

  1. Launch a web browser and head to the Java website to download Java.
  2. Now click on the Agree and Start Free Download.
    Download Java
  3. Then select the download as per the OS and system. Keep in mind if the problematic application, game, or website uses a particular version of Java, then make sure to download the required version.
  4. Afterward, wait till the Java download completes.
  5. Once downloaded, close all browser windows and any other running applications.
  6. Now right-click on the downloaded installer of Java and select Run as Administrator.
  7. Then follow the prompts on the screen to install Java and once done, restart your system.
  8. Upon restart, set up the Java installation as per the (if any) requirements of the problematic application, game, or website (like Environmental Variable, etc.).
  9. Now launch the problematic application, game, or website (in a browser) and check the issue is solved.

Update the System’s Java Version to the Latest Build

If the Java version on the system is outdated, it may cause incompatibility with the problematic website or application. Due to this incompatibility, certain Java-related modules may fail to execute properly and cause error 500. Here, updating the Java version of the system to the latest build may solve the problem.

  1. Press the Windows key and search for Java.
    Open Configure Java
  2. Then in the search results, open Configure Java and head to the Update tab.
    Click Update Java in the Update Tab
  3. Now click on the Update Now button and wait till the update process completes.
  4. Once done, restart your system and upon restart, check if the Java.Lang.NullPointerException issue is cleared.

Disable the System’s Firewall

You may encounter this error message if the system’s firewall is blocking the execution of certain Java modules as the blocked Java modules may fail to execute. In this case, disabling the system’s firewall may clear the error 500. For illustration, we will discuss the process of disabling ESET.

Warning:

Proceed at your own risk as disabling the system’s firewall may expose the system, network, and data to threats.

  1. Right-click on ESET in the hidden icons of the system’s tray and click on Pause Protection.
    Pause ESET Protection and Firewall
  2. Then click Yes (if a UAC prompt is shown) and afterward, select the time interval (like 1 hour) for which you want to disable the firewall.
  3. Now click on Apply and again, right-click on ESET.
  4. Then select Pause Firewall and afterward, confirm to disable ESET firewall.
  5. Now check if the system is clear of the error 500.

Reinstall IDE or Code Editor on the System

For a developer, if none of the code or server-side issues are causing the error message, then the corrupt installation of the IDE (like Adobe ColdFusion) or code editor could be the root cause of the issue.

Here, reinstalling the IDE or code editor may clear the error at hand. For illustration, we will discuss the process of reinstalling Adobe ColdFusion on a Windows PC. Before proceeding, make sure to back up essential code snippets or other data.

  1. Firstly, check if using the default skin or theme (like metallic) of the IDE or Code Editor (like SNAP editor) clears the error.
  2. If not, right-click Windows and open Apps & Features.
    Open Apps & Features
  3. Now expand the Adobe ColdFusion option and select Uninstall.
    Uninstall Adobe ColdFusion
  4. Then confirm to uninstall the Adobe ColdFusion and follow the prompts on the screen to uninstall it.
  5. Once done, restart your system and upon restart, right-click Windows.
  6. Now select Run and then delete the ColdFusion remnants from the following directories:
    temp
    
    %temp%
    
    %ProgramData%
    
    Program Files
    
    Program Files (x86)
    
    appdata

    Open the ProgramData Folder
  7. Then reinstall Adobe ColdFusion and check if the error 500 is cleared.

Reinstall the Problematic Game

You may encounter the ‘error 500:Java.lang.nullpointerexception’ on a Java-based game (like Minecraft) if the game’s installation is corrupt as the game’s modules are not able to perform the designated role. In this scenario, reinstalling the problematic game may clear the error at hand. For elucidation, we will discuss the process of reinstalling Minecraft.

  1. Right-click Windows and open Run.
    Open the Run Command Box from the Quick Access Menu
  2. Now navigate to the following:
    %appdata%
  3. Now open the .Minecraft folder and backup the Saves folder (to save the worlds you have been playing).
    Copy the Saves Folder to the Minecraft
  4. Then click Windows and search for Minecraft.
  5. Now right-click on it and select Uninstall.
    Uninstall Minecraft
  6. Then confirm to uninstall Minecraft and follow the prompts on the screen to uninstall the game.
  7. Once uninstalled, reboot your system and upon reboot, steer to the following path in Run:
    %appdata%
  8. Then delete the .Minecraft folder and afterward, steer to the following path in Run:
    AppData

    Delete the Minecraft Folder in the Roaming Directory
  9. Then delete all the Minecraft-related folders from all of the three following directories:
    Local
    
    LocalLow
    
    Roaming
  10. Now reinstall Minecraft by using the official Minecraft installer and once reinstalled, check if the game is clear of the error 500.

Reinstall Java on the System

If the Java’s installation on your system itself is corrupt, then that can also be the cause of the issue as many of the Java libraries may not be available to the problematic game, application, or website. In this scenario, reinstalling Java on your system may clear the error 500. For illustration, we will discuss the process of reinstalling Java on a Windows system.

  1. Right-click Windows and open Apps & Features.
  2. Now expand the Java option and click on Uninstall.
    Uninstall Java 64-bit Version
  3. Then confirm to uninstall Java and follow the prompts on the screen to uninstall Java.
  4. Once uninstalled, restart your system, and upon restart, open the Run command box by pressing Windows + R keys.
  5. Now delete the Java remnants from the following paths:
    C:Program FilesJava
    
    C:ProgramDataOracleJava
    
    C:Program Files (x86)Common FilesJava
    
    C:Program Files (x86)OracleJava
    
    ProgramData
    
    AppData
    
    temp
    
    %temp%
  6. Afterward, disable the system’s firewall (as discussed earlier) and reinstall the latest Java version (or the Java version required by the game, application, or website).
  7. Once reinstalled, restart your system and upon restart, hopefully, the system would be cleared of the error 500:Java.lang.nullpointerexception.
  8. If not, check if copying the msvcr71.dll file (from another working computer) to the following path clears the error (if the issue is occurring in a browser):
    C:windowssystem32

If the issue persists and occurs with a particular website, application, or game, then you may contact support to check the backend for any server-side issues.

Photo of Kevin Arrows

Kevin Arrows

Kevin Arrows is a highly experienced and knowledgeable technology specialist with over a decade of industry experience. He holds a Microsoft Certified Technology Specialist (MCTS) certification and has a deep passion for staying up-to-date on the latest tech developments. Kevin has written extensively on a wide range of tech-related topics, showcasing his expertise and knowledge in areas such as software development, cybersecurity, and cloud computing. His contributions to the tech field have been widely recognized and respected by his peers, and he is highly regarded for his ability to explain complex technical concepts in a clear and concise manner.

Когда вы объявляете переменную ссылочного типа, на самом деле вы создаете ссылку на объект данного типа. Рассмотрим следующий код для объявления переменной типа int:

int x;
x = 10;

В этом примере переменная x имеет тип int и Java инициализирует её как 0. Когда вы присвоите переменной значение 10 (вторая строка), это значение сохранится в ячейке памяти, на которую ссылается x.

Но когда вы объявляете ссылочный тип, процесс выглядит иначе. Посмотрим на следующий код:

Integer num;
num = new Integer(10);

В первой строке объявлена переменная num, ее тип не относится к встроенному, следовательно, значением является ссылка (тип этой переменной, Integer, является ссылочным типом). Поскольку вы еще не указали, на что собираетесь ссылаться, Java присвоит переменной значение Null, подразумевая «Я ни на что не ссылаюсь».

Во второй строке, ключевое слово new используется для создания объекта типа Integer. Этот объект имеет адрес в памяти, который присваивается переменной num. Теперь, с помощью переменной num вы можете обратиться к объекту используя оператора разыменования ..

Исключение, о котором вы говорите в вопросе, возникает, если вы объявили переменную, но не создали объект, то есть если вы попытаетесь разыменовать num до того, как создали объект, вы получите NullPointerException. В самом простом случае, компилятор обнаружит проблему и сообщит, что

num may not have been initialized

Что говорит: «возможно, переменная num не инициализирована».

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

public void doSomething(Integer num){
   // Работаем с num
}

В этом случае создание объекта (переменная num) лежит на вызывающем коде, то есть вы предполагаете, что он был создан ранее – до вызова метода doSomething. К сожалению, следующий вызов метода вполне возможен:

doSomething(null);

В этом случае значение переменной num будет null. Лучшим способом избежать данного исключения будет проверка на равенство нулю. Как результат, функция doSomething должна быть переписана следующим образом:

public void doSomething(Integer num){
    if (num != null) {
       // Работаем с num
    }
}

Как альтернативный вариант предыдущему примеру вы можете сообщить вызывающему коду, что метод был вызван с неверными параметрами, например, с помощью IllegalArgumentException.

public void doSomething(Integer num){
    if (num == null)
        throw new IllegalArgumentException("Num не должен быть null"); 
    // Работаем с num
}

Также, обратите внимание на вопрос «Что такое stack trace и как с его помощью находить ошибки при разработке приложений?».

Перевод ответа «What is a Null Pointer Exception, and how do I fix it?» @Vincent Ramdhanie.

Довольно часто при разработке на 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 и как эффективно предотвращать такие ситуации при разработке программ.

Понравилась статья? Поделить с друзьями:
  • Ошибка браузера err cert authority invalid
  • Ошибка браузера 404 что это
  • Ошибка брандмауэра torchlight 2 windows 10
  • Ошибка брандмауэра 0x8007042c windows 10
  • Ошибка брак муфты трасса м