I heard from the teacher that most of the abnormalities in future studies are null pointer exceptions. So take some time to play games to check what is a null pointer exception
1: The main reasons for the occurrence of null pointer exceptions are as follows:
(1) When an object does not exist, it will generate an exception obj.method() // The obj object does not exist
(2) When accessing or modifying a field that does not exist in an object, an exception will be generated obj.method() // The method does not exist
(3) The string variable is not initialized;
(4) Interface type objects are not initialized with specific classes, such as:
List lt; will report an error
List lt = new ArrayList(); there will be no error
When the value of an object is empty, you do not judge to be empty. You can try adding a line of code before the following code:
if(rb!=null && rb!="")
Change to:
if(rb==null); if(rb!==null&&rb!="") or if(("").equals(rb))Solution to null pointer:
Focus on the line where the error occurs, and diagnose specific errors through two main reasons caused by the null pointer exception. At the same time, in order to avoid the occurrence of null pointers, it is best to place "null" or null values before the set value when doing judgment processing.
A brief analysis of common null pointer exceptions:
(1) Null pointer error Java.lang.NullPointerException
There are 8 basic data types in Java. The values of variables can have their default values. If they are added without normal assignment, the Java virtual machine cannot be compiled correctly. Therefore, using basic Java data types generally will not cause null pointer exceptions. In actual development, most null pointer exceptions are mainly related to object operations.
2. Java exception handling mechanism
There are two ways to deal with the code that may have exceptions:
First, use the try...catch statement in the method to catch and handle exceptions. The cache statement can have multiple ones to match multiple exceptions. For example:
public void p(int x){try{...}catch(Exception e){...} finally{...}} Second, for exceptions that cannot be processed or those that need to be transformed, pass it at the declaration of the method.
The throws statement throws an exception. For example:
public void test1() throws MyException{...if(....){throw new MyException();}}If each method simply throws an exception, in a multi-layer nested call to the method call method, the Java virtual machine searches back from the method code block where the exception occurs until the code block that handles the exception is found. Then hand the exception to the corresponding 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 code block that handles the exception is still not found, the following steps will be handled:
First, call the printStackTrace() method of the exception object and print the exception information of the method call stack.
Second, if the thread that occurs exception is the main thread, the entire program run terminates; if it is not the main thread, the thread is terminated and other threads continue to run.
Through analysis and thinking, we can see that the earlier the abnormal processing, the smaller the resources and time consumed, the smaller the scope of the impact. Therefore, don't throw exceptions you can handle to the caller as well.
Another point cannot be ignored: finally statements must execute code in any case, which can ensure the reliability of some code that must be executed in any case. For example, when the database query is abnormal, the JDBC connection should be released, etc. The finally statement is executed before the return statement, regardless of its order or location, or whether there is an exception in the try block. The only situation where the finally statement is not executed is that the method executes the System.exit() method. System.exit() functions to terminate the currently running Java virtual machine. The return value of the return cannot be changed by assigning a new value to the variable in the finally statement block. It is also recommended not to use the return statement in the finally block. It is meaningless and can easily lead to errors.
Finally, you should also pay attention to the syntax rules for exception handling:
First, try statements cannot exist alone, but can be composed of catch and finally
try...catch...finally, try...catch, try...finally, try...finally, catch statements can have one or more, and finally statements can be at most one. The three keywords try, catch, and finally cannot be used alone.
Second, the scope of the variables in the three code blocks is independent and cannot be accessed from each other. If you want to be accessible in all three blocks, you need to define the variable outside of these blocks.
Third, when multiple catch blocks are used, the Java virtual machine matches one of the exception class or its subclass, and executes the catch block without executing other catch blocks.
Fourth, there are no other statements that follow after the throw statement because these do not have the opportunity to be executed.
Fifth, if one method calls another method that declares the exception thrown, then this method either handles the exception or declares the thrown.
2.2Difference between throw and throws keywords:
throw is used to throw an exception, inside the method body. The syntax format is: throw exception object.
throws is used to declare what exception may be thrown by a method. After the method name, the syntax format is:
throws Exception type 1, Exception type 2...Exception type n.
Three: The following lists several situations and corresponding solutions where null pointer exceptions may occur:
Code Snippet 1:
out.println(request.getParameter("username"));Analysis: The function of code segment 1 is very simple, which is to output the value of the user input "username".
Note: It seems that the above statement cannot find any syntax errors, and in most cases, there is no problem. However, if a user does not provide the value of the form field "username" when entering data, or bypasses the form directly input through some way, the value of this request.getParameter("username") is empty (note that it is not an empty string, it is an empty object null.), the println method of the out object cannot be directly operated on the empty object, so the JSP page where code segment 1 is located will throw a "Java.lang.NullPointerException" exception. Moreover, even if the object may be empty, some methods of the Java.lang.Object or Object object itself are called, such as toString(), equal(Object obj) and other operations.
Code Snippet 2:
String userName = request.getParameter("username"); If (userName.equals("root")) {...}Analysis: The function of code segment 2 is to detect the username provided by the user. If it is a user whose user name is "root", some special operations will be performed.
Note: In code segment 2, if a user does not provide the value of the form field "username", the string object userName is a null value, and one null object cannot be directly compared with another object. Similarly, the JSP page where code segment 2 is located will throw a empty pointer error.
A small trick: If you want to compare the return value of a certain method with a constant and put the constant in front of it, you can avoid calling the equals method of the null object. for example:
If ("root".equals(userName)) {...}Even if the userName object returns a null object, there will be no null pointer exceptions here and can run as usual.
Snippet 3:
String userName = session.getAttribute("session.username").toString();Analysis: The function of code segment 3 is to take out the value of session.username in the session and assign the value to the string object userName.
Note: In general, if the user has already had a session, no problem will occur; however, if the application server restarts at this time and the user has not logged in again (it may also be that the user closes the browser but still opens the original page.) Then, the value of the session will be invalid at this time, causing the value of session.username in the session to be empty. Direct execution of toString() operation on an object with null will cause the system to throw a null pointer exception.
Snippet 4:
public static void main(String args[]){ Person p=null; p.setName("Zhang San"); System.out.println(p.getName()); }Analysis: Declare a Person object and print out the Name name in the object.
Note: At this time, your p will have a null pointer exception, because you just declared that this Person type object did not create an object, so there is no address reference in its heap. Do not necessarily create an object when using the object and using the method.
A: Start using it directly regardless of whether the object is empty or not.
(JSP) code segment 1:
out.println(request.getParameter("username"));Analysis: The function of code segment 1 is very simple, which is to output the value of the user input "username".
Note: It seems that the above statement cannot find any syntax errors, and in most cases, there is no problem. However, if a user does not provide the value of the form field "username" when entering data, or bypasses the form directly input through some way, the value of this request.getParameter("username") is empty (note that it is not an empty string, it is an empty object null.), the println method of the out object cannot be directly operated on the empty object, so the JSP page where code segment 1 is located will throw a "Java.lang.NullPointerException" exception. Moreover, even if the object may be empty, some methods of the Java.lang.Object or Object object itself are called, such as toString(), equal(Object obj) and other operations.
(JSP) Snippet 2:
String userName = request.getParameter("username"); If (userName.equals("root")){...}Analysis: The function of code segment 2 is to detect the username provided by the user. If it is a user whose user name is "root", some special operations will be performed.
Note: In code segment 2, if a user does not provide the value of the form field "username", the string object userName is a null value, and one null object cannot be directly compared with another object. Similarly, the JSP page where code segment 2 is located will throw a (Java.lang.NullPointerException) null pointer error.
(JSP) Snippet 3:
String userName = session.getAttribute("session.username").toString();Analysis: The function of code segment 3 is to take out the value of session.username in the session and assign the value to the string object userName.
Note: In general, if the user has already had a session, no problem will occur; however, if the application server restarts at this time and the user has not logged in again (it may also be that the user closes the browser but still opens the original page.) Then, the value of the session will be invalid at this time, causing the value of session.username in the session to be empty. Direct execution of toString() operation on an object that is null will cause the system to throw a (Java.lang.NullPointerException) null pointer exception.
The above is the full content of the brief discussion on java exception handling of null pointer exceptions brought to you by the editor. I hope everyone will support Wulin.com more~