일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- reactor core
- 서버운영
- 웹 커리큘럼
- 웹 스터디
- Spring Framework
- Spring Batch
- 웹앱
- reactive
- reactor
- ipTIME
- 공유기 서버
- spring reactive
- Today
- Total
Hello World
java.lang.NullPointerException – How to handle Null Pointer Exception 본문
java.lang.NullPointerException – How to handle Null Pointer Exception
EnterKey 2016. 1. 10. 12:23n Java, a special
value can be assigned to an object’s reference and denotes that the object is currently pointing to unknown piece of data. A is thrown when an application is trying to use or access an object whose reference equals to . The following cases throw that exception:- Invoking a method from a object.
- Accessing or modifying a object’s field.
- Taking the length of , as if it were an array.
- Accessing or modifying the slots of object, as if it were an array.
- Throwing , as if it were a value.
- When you try to synchronize over a object.
The
is a and thus, the compiler does not force you to use a try-catch block to handle it appropriately.Why do we need the null value?
As already mentioned, Null Object pattern and Singleton pattern. The Null Object pattern provides an object as a surrogate for the lack of an object of a given type. The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.
is a special value used in Java. It is extremely useful in coding some design patterns, such asFor example, a sample way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:
TestSingleton.java:
In this example, we declare a static instance of the Singleton class. That instance is initialized at most once inside the
method. Notice the use of the value that enables the unique instance creation.How to avoid the NullPointerException
In order to avoid the
, ensure that all your objects are initialized properly, before you use them. Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object.Also, if the exception is thrown, use the information residing in the exception’s stack trace. The execution’s stack trace is provided by the JVM, in order to enable the debugging of the application. Locate the method and the line where the exception was caught and then, figure out which reference equals to null in that specific line.
In the rest of this section, we will describe some techniques that deal with the aforementioned exception. However, they do not eliminate the problem and the programmer should always be careful while coding an application.
1. String comparison with literals
A very common case in an application’s execution code involves the comparison between a String variable and a literal. The literal may be a String or the element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. For example, observe the following case:
The above code snippet will throw a
. However, if we invoke the method from the literal, the execution flow continues normally:2. Check the arguments of a method
Before executing the body of your own method, be sure to check its arguments for null values. Continue with the execution of the method, only when the arguments are properly checked. Otherwise, you can throw an
and notify the calling method that something is wrong with the passed arguments.For example:
3. Prefer String.valueOf() method instead of toString()
When your application’s code requires the String representation of an object, avoid using the object’s
method. If your object’s reference equals to , a will be thrown.Instead, consider using the static
method, which does not throw any exceptions and prints , in case the function’s argument equals to .4. Use the Ternary Operator
The
operator can be very useful and can help us avoid the . The operator has the form:First, the boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the
operator for handling null pointers as follows:The message variable will be empty if
’s reference is null. Otherwise, if points to actual data, the message will retrieve the first 10 characters of it.5. Create methods that return empty collections instead of null
A very good technique is to create methods that return an empty collection, instead of a
value. Your application’s code can iterate over the empty collection and use its methods and fields, without throwing a . For example:Example.java
6. Make use of Apache’s StringUtils class
Apache’s
is a library that provides helper utilities for the API, such as String manipulation methods. A sample class that provides String manipulation is , which handles input Strings quietly.You can make use of the
and methods, in order to avoid the . For example:7. Use the contains(), containsKey(), containsValue() methods
If your application code makes use of collections, such as
, consider using the contains, and methods. For example, retrieve the value of a specific key, after you have verified its existence in the map:In the above snippet, we don’t check if the key actually exists inside the
and thus, the returned value can be . The safest way is the following:8. Check the return value of external methods
It is very common in practice to make use of external libraries. These libraries contain methods that return a reference. Make sure that the returned reference is not
. Also, consider reading the Javadoc of the method, in order to better understand its functionality and its return values.9. Use Assertions
Assertions are very useful while testing your code and can be used, in order to avoid executing code snippets that will throw a
. Java Assertions are implemented with the assert keyword and throw an .Notice that you must explicitly enable the assertion flag of the JVM, by executing it with the
argument. Otherwise, the assertions will be completely ignored.A sample example using Java assertions is the following:
If you execute the above code snippet and pass a null argument to
, the following error message will appear:Finally, you can use the
class provided by the testing framework.10. Unit Tests
Unit tests can be extremely useful while testing the functionality and correctness of your code. Devote some time to write a couple tests cases that verify that no
is thrown, while your application’s code undergoes a specific execution flow.Existing NullPointerException safe methods
1. Accessing static members or methods of a class
When your code attempts to access a static variable or method of a class, even if the object’s reference equals to
, the JVM does not throw a . This is due to the fact that the Java compiler stores the static methods and fields in a special place, during the compilation procedure. Thus, the static fields and methods are not associated with objects, rather with the name of the class.For example, the following code does not throw a
:TestStatic.java:
Notice, that despite the fact that the instance of the
equals to , the method will be executed properly. However, when it comes to static methods or fields, it is better to access them in a static way, such as .2. The instanceof operator
The
operator can be used, even if the object’s reference equals to . The operator returns false when the reference equals to null and does not throw a . For example consider the following code snippet:The result of the execution is, as expected:
This was a tutorial on how to handle Java’s .
출처: http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception
'Java > Core' 카테고리의 다른 글
Java 7: How to write really fast Java code (0) | 2016.01.10 |
---|---|
[펌]JMeter Tutorial for Load Testing – The ULTIMATE Guide (0) | 2016.01.10 |
[펌]Java Inheritance example (0) | 2016.01.10 |
[펌]Java로 OTP 구현하기 (0) | 2016.01.10 |
[펌]Java Annotations Tutorial – The ULTIMATE Guide (0) | 2016.01.10 |