Discussion on null pointer exceptions for java exception handling

  • 2020-05-12 02:35:01
  • OfStack

Listen to the teacher said, in the following study, most of the exceptions are null pointer exceptions. So tap the game time to query 1 what is null pointer exception

1. The main reasons for null pointer exception are as follows:

(1) when an object does not exist, calling its method will generate an exception obj.method () // obj object does not exist

(2) an exception obj.method () // method method does not exist when accessing or modifying a field that does not exist in an object

(3) string variable is not initialized;

(4) objects of interface type are not initialized with concrete classes, such as:

List lt; complains
List lt = new ArrayList(); You don't get an error

When the value of an object is null, you do not judge it to be null. You can try adding one line of code before the following:


if(rb!=null && rb!="") 

To:


if(rb==null); 
if(rb!==null&&rb!="")  or if(( "" ).equals(rb)) 

Null pointer solution:

Focus on the row where the error was reported, and diagnose specific errors through the two main causes of null-pointer exceptions. At the same time, in order to avoid the occurrence of null pointer, it is better to put "null" or null value before the set value when making judgment processing.

A brief analysis of common null pointer exceptions:

(1) null pointer error Java.lang.NullPointerException

For the 8 basic data types in Java, the value of the variable can have its default value, and the java virtual machine will not compile correctly without assigning it a normal value. Therefore, using the basic Java data type 1 will not cause null pointer exceptions. In practice, most null-pointer exceptions are related to the operation of an object.

2. Java exception handling mechanism

There are two ways to handle code that might be unusual:

1. Use try... The catch statement catches and handles exceptions, and the catach statement can have multiple to match multiple exceptions. Such as:


public void p(int x){
try{
...
}catch(Exception e){
...
}finally{
...
}}

2. For exceptions that cannot be handled or that are to be transformed, pass at the method declaration

The throws statement throws an exception. Such as:


public void test1() throws MyException{
...
if(....){
throw new MyException();
}}

If each method simply throws an exception, then in a multi-layer nested call to the method invocation method, Java virtual looks back from the block of method code where the exception occurs until it finds the block of code that handles the exception. The exception is then passed to the appropriate catch statement for processing. If the Java virtual machine traces back to the main() method at the bottom of the method call stack, if the block of code that handles the exception is still not found, follow these steps:

1. Call the printStackTrace() method of the exception object, and print the exception information of the method call stack.

2. If an abnormal thread appears as the main thread, the whole program will terminate. If the main thread is not, the thread is terminated and the other threads continue to run.

Through analysis and thinking, it can be seen that the earlier the processing of exceptions consumes less resources and time, and the smaller the scope of impact. Therefore, do not throw exceptions to the caller that you can handle.

One more point, which cannot be ignored: the code that the finally statement must execute in all cases, thus ensuring the reliability of the code that must be executed in all cases. For example, JDBC connections should be freed when a database query is abnormal, and so on. The finally statement is executed before the return statement, regardless of where it comes from and whether there is an exception in the try block. The only situation where the finally statement 1 is not executed is if the method executes the System.exit () method. System.exit () terminates the Java virtual machine that is currently running. You cannot change the return value of return by assigning a new value to a variable in an finally block. It is also recommended that you do not use return in an finally block.

Finally, notice the following syntax rules for exception handling:

1. try cannot exist alone, but can be formed with catch and finally

try... catch... finally, try... catch, try... There are three structures of finally. The catch statements can have one or more, and the finally statements can have at most one. The three keywords try, catch and finally cannot be used alone.

2. The scope of the variables in try, catch and finally are independent and cannot be accessed by each other. If you want to be accessible in all three blocks, you need to define variables outside of those blocks.

3. When there are more than one catch block, the Java virtual machine matches one of the exception classes or subclasses, and this catch block is executed and no other catch block is executed.

Statement 4. throw is not allowed to be followed by other statements because there is no chance of execution.

5. If one method calls another method that declares an exception, the method either handles the exception or declares it.

2.2 differences between throw and throws keywords:

throw is used to throw an exception inside the method body. The syntax is: throw exception object.

throws is used to declare what exceptions a method might throw. After the method name, the syntax is:

throws exception type 1, exception type 2... Exception type n.

3. The following lists several situations where null pointer exception may occur and the corresponding solutions:

Code snippet 1:


out.println(request.getParameter("username")); 

Analysis: the function of code segment 1 is 10 points simple, is to output the user input "username" value.

Note: it seems that the above statements are grammatically correct and, in most cases, not problematic. However, this request.getParameter ("username") value is empty if a user enters data without providing the value of the form field "username", or enters it directly bypassing the form in some way. (note that it is not an empty string, but an empty object null.) , the println method of the out object cannot be directly manipulated against an empty object, so the JSP page of code snippet 1 will throw an exception "Java.lang.NullPointerException". And even if the object may be empty, Java.lang.Object or some method of the Object object itself such as toString(), equal(Object obj) are called.

Code snippet 2:


String userName = request.getParameter("username"); 
  If (userName.equals("root")) 
  {....} 

Analysis: the function of code segment 2 is to detect the user name provided by the user, and perform some special operations if the user name is "root".

Note: in code snippet 2, if a user does not provide a value for the form field "username", the string object userName is null. It is not possible to directly compare one null object with another. Similarly, the JSP page where code snippet 2 is located will have a null pointer error.

One tip: if you want to compare the return value of a method to a constant, you can avoid calling the equals method of the null object by putting the constant first. Such as:


If ("root".equals(userName)) 
  {....} 

Even if the userName object returns the null object, there will be no empty pointer exceptions and it will work as usual.

Code snippet 3:


String userName = session.getAttribute("session.username").toString(); 

Analysis: the function of code snippet 3 is to take the value of session.username in session and assign it to the string object userName.

Note: in the 1 case, if the user is already in a session, there will be no problem; However, if the application server is restarted and the user has not yet logged in (or if the user closes the browser but still opens the original page). Then, the value of session will be invalid, and the value of session in session will be null. A direct toString() operation on an null object causes the system to throw a null pointer exception.

Code snippet 4:


public static void main(String args[]){ 

Person p=null; 

p.setName(" zhang 3") ;  

System.out.println(p.getName()); 

} 

Analysis: declare an Person object and print out the Name name in the object.

Note: this time your p null pointer exception, because you are only declaring that the Person object did not create the object, so it does not have an address reference in the heap, do not want to use the object to use the method 1 must create the object.

A: start using the object whether it is empty or not.

(JSP) code snippet 1:


out.println(request.getParameter("username"));

Analysis: the function of code segment 1 is 10 points simple, is the output user input "username" value.

Note: it seems that the above statements are grammatically correct and, in most cases, not problematic. However, this request.getParameter ("username") value is empty if a user enters data without providing the form field "username" value, or if he or she bypasses the form in some way and enters it directly. (note that it is not an empty string, but an empty object, null.) , the println method of the out object cannot be manipulated directly against an empty object, so the JSP page of code snippet 1 will throw an exception "Java.lang.NullPointerException". And even if the object may be empty, Java.lang.Object or some method of the Object object itself, such as toString(), equal(Object obj), are called.

(JSP) code snippet 2:


if(rb==null); 
if(rb!==null&&rb!="")  or if(( "" ).equals(rb)) 
0

Analysis: the function of code segment 2 is to detect the user name provided by the user. If the user name is "root", some special operation is performed.

Note: in code snippet 2, if a user does not provide a value for the form field "username", the string object userName is null. It is not possible to directly compare one null object with another. Similarly, the JSP page where code snippet 2 is located will have a null pointer error (Java.lang.NullPointerException).

(JSP) code snippet 3:


if(rb==null); 
if(rb!==null&&rb!="")  or if(( "" ).equals(rb)) 
1

Analysis: the function of code snippet 3 is to take the value of session.username in session and assign it to the string object userName.

Note: in the 1 case, if the user is already in a session, there will be no problem; However, if the application server is restarted and the user has not yet logged in (or if the user closes the browser but still opens the original page). In this case, the value session will be invalid, and the value session in session will be null. A direct toString() operation on an object of null causes the system to throw a null pointer exception (Java.lang.NullPointerException).


Related articles: