English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The teacher said that in the future learning, most of the exceptions are NullPointerExceptions. So take some time to play games to find out what a NullPointerException is
Firstly, the main reasons for the occurrence of NullPointerException are as follows:
(1) An exception will occur when calling a method of an object that does not exist obj.method() // obj object does not exist
(2) An exception will occur when accessing or modifying a non-existent field of an object obj.method() // method method does not exist
(3) String variables are not initialized;
(4) Interface type objects are not initialized with specific classes, for example:
List lt; will cause an error
List lt = new ArrayList(); then there will be no error
When an object's value is empty, you did not judge it as null. You can try to add a line of code before the following code:
if(rb!=null && rb!="")
Change to:
if(rb==null); if(rb!==null&&rb!="") or if((""></b>").equals(rb))
Solutions to NullPointerException:
Focus on the line where the error occurred, diagnose the specific error through the two main reasons for the occurrence of NullPointerException. At the same time, to avoid the occurrence of NullPointerException, it is best to place 'null' or empty values before the set value when making judgments.
A brief analysis of common NullPointerExceptions:
(1)NullPointerException Java.lang.NullPointerException
In Java,8For basic data types, variables can have default values. If they are not assigned normally, the Java Virtual Machine cannot compile correctly, so using basic Java data types generally will not cause a NullPointerException. In actual development, most NullPointerExceptions are mainly related to object operations.
Secondly, Java Exception Handling Mechanism
There are two ways to handle code that may throw exceptions:
Firstly, use try...catch statements to catch and handle exceptions in methods. Catch statements can have multiple ones, used to match multiple exceptions. For example:
public void p(int x){ try{ ... }catch(Exception e){ ... }finally{ ... }}
Secondly, for exceptions that cannot be handled or exceptions that need to be transformed, declare them in the method declaration through
The throws statement throws an exception. For example:
public void test1() throws MyException{ ... if(....){ throw new MyException(); }}
If each method simply throws an exception, then in the multi-layered nested calls of method calling methods, the Java virtual machine will trace back from the code block where the exception occurs to find the code block that handles the exception until it finds it. Then, the exception is handed over 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 when it reaches the bottom, and if there is still no code block to handle the exception, it will handle it according to the following steps:
Firstly, call the printStackTrace() method of the object where the exception occurs to print the exception information of the method call stack.
Secondly, if the thread where the exception occurs is the main thread, the entire program will terminate; if it is not the main thread, the thread will be terminated, and other threads will continue to run.
Through analysis and thinking, it can be seen that the earlier the exception is handled, the less resources and time are consumed, and the smaller the range of impact. Therefore, do not throw exceptions that you can handle to the caller.
Moreover, it is something that should not be ignored: the finally statement must execute code in any case, which ensures the reliability of code that must be executed in any case. For example, when there is an exception in database query, it should release the JDBC connection, etc. The finally statement is executed before the return statement, regardless of their order, whether an exception occurs in the try block or not. The only situation where the finally statement is not executed is when the method executes the System.exit() method. The role of System.exit() is to terminate the current running Java virtual machine. You cannot change the return value of return by assigning a new value to the variable in the finally statement block, and it is also recommended not to use the return statement in the finally block, as it is meaningless and may easily lead to errors.
Finally, pay attention to the syntax rules of exception handling:
Firstly,The try statement cannot exist alone and can be combined with catch and finally.
The three structures of try...catch...finally, try...catch, and try...finally, where the catch statement can have one or more, and the finally statement at most one, and the three keywords try, catch, and finally cannot be used alone.
Secondly,The scope of variables in the try, catch, and finally code blocks is independent and cannot be accessed by each other. If you want to access the variables in all three blocks, you need to define the variables outside these blocks.
Thirdly,When there are multiple catch blocks, the Java virtual machine will match one exception class or its subclass, and then execute the corresponding catch block, without executing other catch blocks.
Fourthly,The throw statement does not allow other statements to follow immediately, as these have no chance to be executed.
Fifthly,If a method calls another method that declares to throw an exception, then this method must either handle the exception or declare to throw it.
2.2The difference between throw and throws keywords:
throw is used to throw an exception, within the method body. The syntax format is: throw exception object.
throws is used to declare what exceptions a method may throw, after the method name, with the syntax format:
throws exception type1, exception type2...exception type n.
Three: The following lists several possible situations where a NullPointerException may occur and their corresponding solutions:
Code Segment1:
out.println(request.getParameter("username"));
Analysis:Code Segment1has a very simple function, which is to output the value of the user input "username".
Note:It seems that the above statement does not find any syntax errors, and in most cases, no problems are encountered. However, if a user does not provide the value of the form field "username" when entering data, or enters directly through some means, the value of request.getParameter("username") will be empty (note that it is not an empty string, but a null object.), and the println method of the out object cannot operate directly on the empty object, so the code segment1The JSP page will throw the "Java.lang.NullPointerException" exception. Moreover, even if the object may be null, some methods of Java.lang.Object or the Object object itself, such as toString(), equal(Object obj), etc., may be called.
Code Segment2:
String userName = request.getParameter("username"); If (userName.equals("root")) {....}
Analysis:Code Segment2The function is to check the username provided by the user. If the username is "root", some special operations will be executed.
Note:In the code segment2If a user does not provide the value of the form field "username", the string object userName will be null, and it is not possible to directly compare a null object with another object. Similarly, the code segment2The JSP page will throw a NullPointerException.
A small trick:If you want to compare the return value of a method with a constant, placing the constant first can avoid calling the equals method of a null object. For example:
If ("root".equals(userName)) {....}
Even if the userName object returns a null object, there will be no null pointer exception here, and it can run normally.
Code Segment3:
String userName = session.getAttribute("session.username").toString();
Analysis:Code Segment3The function is to retrieve the value of session.username in the session and assign it to the string object userName.
Note:In general, if the user has already logged in to a session, there will be no problem; but 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 this session will become invalid at this time, and at the same time, the value of session.username in the session will become null. Direct execution of toString() operation on a null object will cause the system to throw a null pointer exception.
Code Segment4:
public static void main(String args[]){ Person p=null; p.setName("张三"); System.out.println(p.getName()); }
Analysis:Declare a Person object and print the Name in the object.
Note:At this time, your p will appear a null pointer exception because you have only declared the Person type object without creating an object, so there is no address reference in its heap. Be careful to create an object when you need to call the method of the object.
A: Start using the object directly regardless of whether it is null or not.
(JSP) Code Segment1:
out.println(request.getParameter("username"));
Analysis:Code Segment1has a very simple function, which is to output the value of the user input "username".
Note:It seems that the above statement does not find any syntax errors, and in most cases, there are no problems. However, if a user does not provide the value of the form field "username" when entering data, or enters directly through some means bypassing the form, the value of request.getParameter("username") is null (note that it is not an empty string, but a null object.). The println method of the out object cannot operate directly on a null object, so the code segment1The JSP page will throw a "Java.lang.NullPointerException" exception. Moreover, even if the object may be null, it calls some methods of Java.lang.Object or the Object object itself, such as toString(), equal(Object obj), and other operations.
(JSP) Code Segment2:
String userName = request.getParameter("username"); If (userName.equals("root")) {....}
Analysis:Code Segment2The function is to check the username provided by the user. If the user name is "root", some special operations will be executed.
Note:In the code segment2If a user does not provide the value of the form field "username", the string object userName is null, and it is not possible to directly compare a null object with another object. Similarly, the code segment2The JSP page where this code segment is located will throw a (Java.lang.NullPointerException) null pointer error.
(JSP) Code Segment3:
String userName = session.getAttribute ("session.username").toString();
Analysis:Code Segment3The function is to retrieve the value of session.username in the session and assign it to the string object userName.
Note:In general, if a user has already started a session, there will be no problem. 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 this session will become invalid at this time, and it will also cause the value of session.username in the session to be empty. Direct execution of toString() on a null object will cause the system to throw a (Java.lang.NullPointerException) null pointer exception.
This is the full content of the brief introduction to Java exception handling, null pointer exception brought to you by the editor. I hope everyone will support and cheer for the tutorial~