Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null.
What is null?
“null” is a very familiar keyword among all the programmers out there. It is basically a Literal for Reference datatypes or variables like Arrays, Classes, Interfaces, and Enums. Every primitive data type has a default value set to it(Ex: True and False value for Boolean). Similarly, Reference Datatype Variables have Null value as default if it is not initialized during declaration.
Java
import
java.util.Scanner;
public
class
Main
{
public
static
void
main(String[] args) {
Scanner sc =
null
;
System.out.println(sc);
}
}
Output:
null
It is also important to note that we cannot directly store a null value in a primitive variable or object as shown below.
Java
import
java.util.Scanner;
public
class
Main
{
public
static
void
main(String[] args) {
int
i =
null
;
System.out.println(i);
}
}
Output:
Main.java:5: error: incompatible types: cannot be converted to int int i = null; ^ 1 error
What is NullPointerException?
It is a run-time exception that arises when an application or a program tries to access the object reference(accessing methods) which has a null value stored in it. The null value gets stored automatically in the reference variable when we don’t initialize it after declaring as shown below.
Java
import
java.util.Scanner;
public
class
Main
{
public
static
void
main(String[] args) {
Scanner sc =
null
;
int
input =sc.nextInt();
System.out.println(input);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException at Main.main(Main.java:6)
Null Pointer Exception in Android Studio
NullPointerException in Android Studio highlighted in yellow color in the below screenshot
As you can observe from the above picture, it contains a Textview which is initialized to null.
TextView textview = null;
The TextView reference variable(i.e. textview) is accessed which gives a NullPointerException.
textview.setText("Hello world");
The App keeps stopping abruptly
Code
Java
import
androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
MainActivity
extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview =
null
;
textview.setText(
"Hello World"
);
}
}
Handling the NullPointerException in Android Studio
To Handle the NullPointerException smoothly without making the app crash, we use the “Try – Catch Block” in Android.
- Try: The Try block executes a piece of code that is likely to crash or a place where the exception occurs.
- Catch: The Catch block will handle the exception that occurred in the Try block smoothly(showing a toast msg on screen) without letting the app crash abruptly.
The structure of Try -Catch Block is shown below
Code
Java
import
androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
MainActivity
extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview =
null
;
try
{
textview.setText(
"Hello world"
);
}
catch
(Exception e){
Toast.makeText(
this
,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
Output:
Using Try Catch we can catch the exception on the screen
How to fix the NullPointerException?
To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app.
Solving the NullPointerException
TextView with id textview
Code
Java
import
androidx.appcompat.app.AppCompatActivity;
import
android.os.Bundle;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
MainActivity
extends
AppCompatActivity {
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textview = findViewById(R.id.textview);
try
{
textview.setText(
"Hello world"
);
}
catch
(Exception e){
Toast.makeText(
this
,e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
}
Output:
Output after Solving NullPointerException
As you can see after initializing the text view component we have solved the NullPointerException. Hence in this way, we can get rid of NullPointerException in Android Studio.
Last Updated :
25 Jul, 2022
Like Article
Save Article
You have just finished creating an Android-based application and attempt to execute it. As far as you know, the application is fine, there are no syntax errors and the code should just work fine. But when you run it now, your application quits saying an uncaught RuntimeException
was thrown. Attempting to dig up the cause, you find something that gives you a clue: a NullPointerException
has occurred.
With this, you begin your journey into the world of exception handling with Android, in particular, handling NullPointerException
. In this post, we’ll discuss how to fix NullPointerException
s in Android apps.
Jump ahead:
- What is a
NullPointerException
?- Why do
NullPointerException
s occur?
- Why do
- Avoiding
NullPointerException
s in Java- Using SmartCast
- Using the Elvis operator
- Avoiding
NullPointerException
s in Kotlin - Using
logcat
to detect and fix aNullPointerException
in Android Studio - Setting breakpoints to debug
NullPointerException
s
What is a NullPointerException
?
First, let’s quickly refresh ourselves on exceptions. They are events or abnormal conditions in a program that occur during execution and disrupt the normal flow of the program.
An exception can occur for different reasons, such as:
- A user enters invalid data to a field
- A file that must be opened cannot be found
- A network connection is lost in the middle of communication
- The JVM has run out of memory
When an error occurs inside a method, it throws an exception. A NullPointerException
is one of the most common runtime exceptions.
In Java, null
is a special value that represents the absence of a value. When you try to use a null
value, you get a NullPointerException
because the operation you are trying to perform cannot be completed on a null
value.
In Kotlin, null
is not a value, but a type of its own called nullable. By default, every object in Kotlin is non-null, which means it cannot have a null value.
Why do NullPointerException
s occur?
You might encounter a NullPointerException
when trying to access a view, resource, or data that hasn’t been properly initialized or loaded yet. Some of the situations in which a NullPointerException
can occur in Java, according to the Java Language Specification, include:
- Attempting to access elements of a
null
array - Using
switch
with a null expression - Accessing instance fields of
null
references - Invoking instance methods of a
null
reference - Using an integer or floating point operator that has one of its operands as a boxed
null
reference - Attempting an unboxing conversion with the boxed value as
null
- Calling
super
on anull
reference
Avoiding NullPointerException
s in Java
Below are some best practices to avoid NullPointerException
s in Java:
- String comparison with literals
- Avoid returning null from your methods
- Keep checking arguments of methods
- Use
String.valueOf()
rather thantoString()
- Using primitives data types as much as possible
- Avoid chained method calls
- Use ternary operator
By contrast, Kotlin is a smarter, more modern language that has been designed to avoid NullPointerException
s through several mechanisms, such as:
- Using nullable and non-nullable types
- Using the SmartCast feature
- Safe calls
- The Elvis operator
In Kotlin, all regular types are non-nullable unless you explicitly mark them as nullable with a question mark ?
, e.g., String?
.
Consider the below Kotlin code:
fun getlen(name: String) = name.length
The parameter name
has a type of String
, which means it must always contain a String
instance and cannot contain null
. This code ensures that a NullPointerException
at runtime is unlikely to occur.
Instead, any attempt to pass a null
value to the getlen(name: String)
function will cause a compile-time error: Null cannot be a value of a non-null type String
. This is because the compiler has enforced the rule that arguments of getlen()
cannot be null.
Consider the below snippet, in which the code is obvious to us but may not be immediately obvious to the compiler:
class TestNPE { companion object { @JvmStatic fun main(args: Array<String>) { var m : String? // here, m is declared as nullable println("m is : $m") var x: Int x = 150 if (x == 150) println("Value of m is : $m") } } }
The compiler raises a compiler error because m
is not initialized:
Thus, instead of proceeding to runtime and then raising an exception, it stops at the compilation stage with a compiler error.
Using SmartCast
In order to use nullable types, Kotlin has an option called safe cast, or smart cast. Through this feature, the Kotlin compiler will trace situations inside if
and other conditional expressions. So, if the compiler finds a variable belonging to a non-null type, it will allow you to access this variable safely.
In certain cases, it is not possible for the compiler to cast types, in which case it will throw an exception; this is called unsafe casting. Consider a nullable string (String?
) which cannot be cast to a non-nullable string (String
). It will throw an exception.
Kotlin addresses this by providing a safe cast operator as?
to cast safely to another type. If casting is not possible, it returns a null
rather than throwing a ClassCastException
.
Example:
val aInt: Int? = a as? Int
Using the Elvis operator ?:
Kotlin also has an advanced operator called the Elvis operator (?:
) that returns either a non-null value or the default value, even if the conditional expression is null. It also checks the null safety of values.
Consider an example:
val count = attendance?.length ?: -1
This means:
val count: Int = if (attendance != null) attendance.length else -1
Despite this, an NullPointerException
could still occur in Kotlin-based Android applications.
Consider the earlier example of class TestNPE
. Now, the code is modified such that m
is initialized but is used with a non-null assertion operator (!!
), which converts a given value to a non-null type and throws an exception if the value is null
.
class TestNPE { companion object { @JvmStatic fun main(args: Array<String>) { var m: String?=null // here, m is declared //as nullable var x: Int x = 150 if (x == 150) println("m is : $m") var mlen = m!!.length println("length of m is : $mlen") } } }
In this case, a NullPointerException
will be thrown, as shown here:
Avoiding NullPointerExceptions
in Kotlin
A few causes of a NullPointerException
in Kotlin are:
- Explicitly calling
throw NullPointerException()
- Using the
!!
operator - Data inconsistency with regard to initialization
- Java interoperation
To prevent NullPointerException
s, you should always ensure that your variables and objects are properly initialized before you use them. You can also use null checks or try … catch
blocks to handle possible null values and prevent your app from crashing.
An extremely simplified example of using try … catch
is given below:
class TestNPE { companion object { @JvmStatic fun main(args: Array<String>) { var m: String?=null // here, m is declared //as nullable try { var x: Int x = 150 if (x == 150) println("m is : $m") var mlen = m!!.length println("length of m is : $mlen") }catch( ne: NullPointerException) { println("Null Pointer Exception has occurred. ") } } } }
The code that is likely to cause a NullPointerException is enclosed in a try … catch
block.
The advantage here is that the developer has control over what must be done when the exception is thrown. Here, a simple message is displayed. In practical scenarios, one can close any currently open resources, such as files, before terminating the program.
Using logcat
to detect and fix a NullPointerException
in Android Studio
Whenever an Android application crashes, a stack trace is written to the console that contains vital information that can help identify and solve the issue. There are two ways to get to this stack trace:
-
- Using Google’s
adb
shell utility to obtain alogcat
file, which can help explain why the application crashed:adb logcat > logcat.txt
Open
logcat.txt
and search for the application name. It will have information on why the application failed along with other details such as line number, class name, and so on - In Android Studio, either press
Alt + 6
, or click the Logcat button in the status bar. Make sure your emulator or device is selected in the Devices panel, then locate the stack trace.
- Using Google’s
There may be a lot of stuff logged into logcat
, so you may need to scroll a bit, or you can clear the logcat
through the Recycle Bin option and let the app crash again to bring the most recent stack trace in the log to the top.
An important point of note is that if your app is already live, then you cannot use logcat
.
Android Studio Electric Eel’s latest version has an updated logcat
, which facilitates easier parsing, querying, and tracking of logs. The new logcat
also:
- Formats logs for easy scanning for tags, messages, and other useful information
- Identifies various types of logs, such as warnings and errors.
- Makes it easier to track logs from your app across app crashes and restarts
When logcat
notices that your app process has stopped and restarted. you’ll see a message in the output similar to below:
PROCESS ENDED
Or:
PROCESS STARTED
Developers can fine tune the command to give the message timestamp, for example:
adb logcat -v time
Using logcat
, you can determine whether a widget or component is declared but not defined yet, or a variable is null
and being used. Sometimes, it could happen that a context is null
during navigation between screens, and you are attempting to use that context without realizing it’s null
.
Setting breakpoints to debug NullPointerException
If you have a large application, it can be quite cumbersome to debug it. You can set breakpoints in your code that let you debug your code block by block.
A breakpoint serves as a stop sign for the marked piece of code. When a breakpoint is encountered during application debugging, it will pause execution, thus enabling allowing developers to examine in detail what’s happening and use other debugging tools as required.
To use breakpoints, add a breakpoint by clicking the gutter in the code editor next to the line number where you want execution to pause. A dot will appear next to the line number, and the line will be highlighted. See below; two breakpoints are added:
Click Run > Debug ‘app’. The program halts at the first breakpoint and you can examine the values in the Debug window at the bottom of Android Studio:
There are various buttons such as Step Over and Step Into that can help you navigate further:
Besides examining the current values of certain operands and expressions, you can also evaluate expressions using the Evaluate option.
In the below example, I wanted to know what the value of x
added to 100 would be. The window shows me the result based on the current value of x
:
Here is a detailed explanation of various terms related to debugging in Android Studio.
Conclusion
To conclude, in Android development, there are various mechanisms available with Java and Kotlin that are designed to aid developers in avoiding NullPointerException
s. In the cases these exceptions still occur, you should now have a variety of tools that help identify the cause and debug code.
LogRocket: Instantly recreate issues in your Android apps.
LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.
LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket’s product analytics features surface the reasons why users don’t complete a particular flow or don’t adopt a new feature.
Start proactively monitoring your Android apps — try LogRocket for free.
I’m new to android/java programming and am confused how to properly deal with this warning.
Method invocation ” may produce ‘Java.lang.NullPointerException’
Should I be ussing assert to remove the warning?
Or rather a runtime exception?
Any help would be appreciated.
asked Apr 29, 2014 at 17:57
4
I doubt this question can be answered conclusively, as it’s a matter of opinion. Or at least I believe so — an opinion too. 🙂
I understand you want “0 warnings” (a very laudable goal) but there’s probably not a “one size fits all” issue. That said…
Things I believe you should not do:
- Use assert. While you can add an assert statement, Dalvik ignores them. You can configure an emulator to use them if you want, but not a real device (see Can I use assert on Android devices?). So while it would possibly remove the warning, it’s useless in practice.
- Have the method throw
NullPointerException
. This would be a bad idea, generally. In this case, since you’re probably overridingonOptionsItemSelected()
, it’s not even possible.
Checking for (variable != null)
is generally the best approach. What to do if it is, though, presents some other options.
- If it’s a problem you can recover from, i.e. you can continue the application even though the
searchView
isn’t there, just do so. For example, just return from the method. It’s a good idea to log this situation though, so you can spot it while testing. - Otherwise, if continuing isn’t possible, throw an exception. You want to fail early, so that the problem can be easily detected. A reasonable exception for this case would be IllegalStateException (see Java equivalent to .NET System.InvalidOperationException). It basically indicates that this method was executed at an inappropriate time. Be careful though, that as a
RuntimeException
, these exceptions are unchecked, and hence will probably cause the app to crash.
Rohit
131 silver badge3 bronze badges
answered Jun 15, 2014 at 5:38
matiashmatiash
54.7k16 gold badges125 silver badges154 bronze badges
5
I started to use
@SuppressWarnings("ConstantConditions")
on simple methods where I’m sure that the id is not null.
answered Jun 8, 2016 at 15:52
Herrbert74Herrbert74
2,52831 silver badges51 bronze badges
2
What @Herrbert74 suggested it surely working fine, but sometimes it’s better to not add a @SuppressWarnings("ConstantConditions")
to an entire method (if it’s not trivial), a better approach could be to use //noinspection ConstantConditions
on the warned line.
Those are my rules of thumb:
Use
@SuppressWarnings("ConstantConditions")
when the method is simpleUse
//noinspection ConstantConditions
when the method is complex and you need to remove the warning only on a specific line
answered Dec 12, 2017 at 8:59
MatPagMatPag
40.9k14 gold badges101 silver badges114 bronze badges
2
I like the answer to this link.
Warning is not an Error. And the warning which you are talking about
says “it may produce”, don’t say ‘it must produce’. So choice is
yours. Either add null check or notSo, If you are sure that findViewById in your code will never be cause
of NPE, then don’t add the null check.
answered Jun 19, 2014 at 0:01
RyhanRyhan
1,8051 gold badge18 silver badges22 bronze badges
I personally prefer using try{ }catch{ } simply because it is more elegant. However, it does add a lot of bulk to your code, if you imagine putting every, possible, NULL value into a try catch (if they are not next to each other)
answered Jun 19, 2014 at 13:13
Georgi AngelovGeorgi Angelov
4,31812 gold badges67 silver badges96 bronze badges
As @matiash pointed out there is no one-size-fits-all solution.
For me a good compromise was to disable NullPointerException
warning for all calls to findViewById()
and keep it for other method calls. That way I take responsibility for checking the resource ids but still get a benefit of getting warnings if I make other mistakes.
To achieve this I added _ -> !null
method contract with Android Studio quick fix menu.
The action generated a following file file at android/support/v7/app/annotations.xml
in my project root.
<root>
<item name='android.support.v7.app.AppCompatActivity android.view.View findViewById(int)'>
<annotation name='org.jetbrains.annotations.Contract'>
<val val=""_ -> !null"" />
</annotation>
</item>
</root>
Update:
Unfortunately it doesn’t survive Android Studio restarts 🙁
External annotations are really useful so I hope I’ll figure out a way to make Android Studio load them after restart.
answered Jul 8, 2016 at 9:24
Iwo BanasIwo Banas
8928 silver badges12 bronze badges
Yes. Using if (Object != null){}
for validating is the proper way. try {} catch (NullPointerException) {}
is the next solution which is preferred in this case.
If you want to get ride of it, throw an NullPointerException
. Lint will ignore it in this case. public void myFunc() throws NullPointerException{}
.
Anyway, good Coding always means validating everything for a possible problem while runtime. Validating != null
is just fine and should always be used whenever it’s possible null.
OneCricketeer
175k18 gold badges130 silver badges238 bronze badges
answered Jun 12, 2014 at 13:31
EmanuelEmanuel
7,9892 gold badges36 silver badges55 bronze badges
I’ve used Objects.requireNonNull()
which is a good way IMO. As @matiash mentioned, this is not a fool-proof way for every use case, but where you are sure that data won’t be null
, you can use this approach to get rid of the warning. And if it does fail for some unknown reason, you will get NullPointerException
which you will get anyway without using this.
// before
cal.setTime(date);
// after
cal.setTime(Objects.requireNonNull(date));
answered Mar 23, 2020 at 8:13
MangeshMangesh
5,3615 gold badges48 silver badges71 bronze badges
In this post, we are going to talk about the NullPointerException in Java. We will discuss the main causes and solution to it. I will also discuss how to track down a NullPointerException in Android Studio. I will try to explain at a high level (no low-level explanations) so it can be easily understood.
What causes a NullPointerException?
A NullPointerException is usually thrown when you try to access a field or a method in a variable or an object that is null. This is simple to understand however, it might be a bit confusing for some programmers.
Now, the next question is:
What causes an object to be null?
When you create a variable or an object without instantiating it, then the value of that variable or object is null. So for example, when you have the following code:
The value of firstName
in this case would be null.
Now if you try to call a method on the variable firstName
, then the NullPointerException will be thrown.
For example:
String firstName; firstName.toLowerCase(); |
The above code will throw a null pointer exception on line 2.
Similarly, if you create an object without equating the object, the ugly null pointer exception will be thrown.
For example:
Game newGame; newGame.start(); |
The above code will throw the NullPointerException.
How to solve the NullPointerException.
To solve the NullPointerException, you simply need to assign a value to the variable involved. If it is an object, you need to instantiate that object with the new
keyword.
For example:
String firstName = “Finco”; firstName.toLowerCase(); |
The above code will work swiftly.
For objects:
Game oldGame = new Game(); oldGame.start(); |
The above code will also work beautifully.
Debugging the NullPointerException in Android
There are times when even professional developers can swear that the object involved cannot just be null. Personally, I used to be guilty of this. There are times when it just seems impossible for the object in question to be null. However, what I would like to assure you is that when your IDE throws the null pointer exception, be sure your IDE is not mistaken :).
So I will list a couple of scenarios that could result in an object being null even when the object involved seems to be not null. Please note that there are hundreds of other scenarios, however, I would discuss just a couple of them.
For simplicity, we will use only objects as examples
Scenario 1:
Sometimes, you might have instantiated a class correctly, but later in your code, unknowingly assigned a null value to that object.
For example:
Game oldGame = new Game(); oldGame.start(); //some other portion of the code oldGame = null; //some further portion of the code oldGame.stop(); |
The above example is an illustration of how a NullPointerException can be caused by “programmer error”.
Scenario 2:
Calling
in an Activity class whose layout does not contain the requested view.findViewById()
This is one of the most common reasons developers encounter the NullPointerException when developing an Android App. Take a look at the code sample below.
public class SplashActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ImageView pb = findViewById(R.id.imgHeartLoading); pb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO: do something } }); } } |
The code above is valid and should not throw any exceptions under normal conditions. However, the id R.id.imgHeartLoading
has to be present in the layout file R.layout.activity_splash
. If the requested view is not present in the R.layout.activity_splash
layout file, then the findViewById()
method will return null. In a scenario where findViewById()
returns null, then the next line pb.setOnClickListener(new View.OnClickListener() {...});
would throw the NullPointerException.
Basically, when you call the findViewById()
method in an Activity class, the method tries to locate the requested view in whatever layout that was passed to setContentView()
. Some developers assume that the findViewById()
method goes through every single layout file in the project, however, this is very wrong.
So in a case like this:
- The variable pb is being equated to
findViewById(R.id.imgHeartLoading)
exist somewhere in the projectR.id.imgHeartLoading
- But the variable pb is still null.
NullPointerException can be avoided in programming by using the following
1. Check for null values before calling an object’s method:
This is a very simple solution. In the example above, we can avoid the NullPointerException by inserting an if statement just before calling setOnClickListener
For Example:
ImageView pb = findViewById(R.id.imgHeartLoading); if(pb != null){ pb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO: do something } }); } |
In this case, the if(){}
block will never be executed if the pb
variable is null
2. Use a try{} catch(){} Block:
This solution simply involves wrapping your code in a try and catch block.
For Example:
ImageView pb = findViewById(R.id.imgHeartLoading); try{ pb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO: do something } }); }catch(Exception ex){ ex.printStackTrace(); } |
Note:
The above solutions are just temporary solutions. These solutions only avoid the NullPointerException but they do nothing to solve the problem. As a good developer, you should track down the main reason for the exception.
And that’s all for now.
If you have any questions or contributions, feel free to post them in the comment box below :).
Related posts:
Довольно часто при разработке на 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 и как эффективно предотвращать такие ситуации при разработке программ.