JAVA basics: Analysis of Several Common Errors in JAVA

Source: Internet
Author: User
JAVA basics: A Brief Analysis of Several Common Errors in JAVA-Linux general technology-Linux programming and kernel information. The following is a detailed description. 1. Null Pointer Error java. lang. NullPointerException

?? When the basic JAVA data type is used, the value of the variable is either the default value. If no value is assigned to the variable, the program cannot be compiled. Therefore, the basic JAVA data type (double, float, boolean, char, int, long) generally does not cause NULL pointer exceptions. It can be seen that Null Pointer exceptions are mainly related to object operations.

?? The following lists the possible situations and solutions for NULL pointer exceptions:

?? You can directly start using an object regardless of whether it is null.

?? (JSP) code Segment 1:
?? Out. println (request. getParameter ("username "));

?? Description:
?? The function of section 1 is very simple, that is, to output the value of the user input table field "username.

?? Note:
?? It seems that no syntax error is found in the preceding statement, 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 directly enters the form by bypassing the form in some way, request. the value of getParameter ("username") is null (not an empty string, it is a null object .), The println method of the out object cannot directly operate on the null object. Therefore, the JSP page where code segment 1 is located will throw a "java. lang. NullPointerException" exception.

?? Even if the Object may be empty, some methods of java. lang. Object or Object itself, such as toString () and equals (Object obj), are called.

?? (JSP) code Segment 2:
?? String userName = request. getParameter ("username ");
?? If (userName. equals ("root "))
?? {....}

?? Description:
?? The function of section 2 is to check the user name provided by the user. If the user name is "root", special operations are 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 and cannot be directly compared with another object, similarly, the JSP page where code snippet 2 is located will throw (java. lang. nullPointerException) NULL pointer error.

?? (JSP) code Segment 3:
?? String userName = session. getAttribute ("session. username"). toString ();

?? Description:
?? The function of section 3 is to extract the value of session. username in the session and assign the value to the string object userName.

?? Note:
?? In general, if a user has already performed a session, no problem will occur. However, if the application server restarts at this time, and the user has not logged on again, (The user may close the browser but still open the original page .) In this case, the session value becomes invalid, and the value of session. username in the session is empty. If you directly perform the toString () operation on a null object, the system throws a null pointer exception (java. lang. NullPointerException.

?? Solution:
?? To ensure that the objects to be operated or referenced are not empty, if we want to operate or reference an object, we first check whether the object has been instantiated and is not empty; in addition, add a processing method for the case where the object is null in the system.

?? For example, the String object is used to save the results submitted by the user. If operations involving objects are performed, the system first checks whether the object is empty and then checks whether the object is empty, you can choose one of the following processing methods:

?? Processing Method 1) when the object is null, set the object value to an empty string or a default value;
?? Processing Method 2) when the object is detected to be null, no operation is performed, and the operation is directly redirected to other processes.
?? Processing Method 3) when the object is null, the system prompts that the user operation has an error.
?? Rewrite code snippet 2 in the above way To get:

?? Method 1:

?? String userName = request. getParameter ("username ");
?? // When the variable value is null, it is converted to a default null string.
?? If (userName = null)
?? UserName = "";
?? If (userName. equals ("root "))
?? {..........}

?? Method 2:

?? String userName = request. getParameter ("username ");
?? // If the variable value is null, it is converted to a default null string without any operation.
?? If (usreName! = Null)
?? {
??? If (userName. equals ("root "))
??? {..........}
??}

?? Method 3:

?? String userName = request. getParameter ("username ");
?? // If the variable value is null, it is converted to a default null string without any operation.
?? If (usreName = null)
?? {
?? // Prompt that user input is blank
??}

?? In practice, the above three methods also apply to the handling of other exceptions:

?? Exception Handling Method 1) Check for exceptions and set the object value to an empty string or a default value.
?? Exception Handling Method 2) if an exception is detected and no operation is performed, the system jumps to another process.
?? Exception Handling Method 3) Check for exceptions and prompt users for Operation errors.

?? 2. incorrect number formatting java. lang. NumberFormatException Analysis

?? (JSP) code Segment 3:
?? String s_memberid = request. getParameter ("memberid ");
?? Int I _memberid = Integer. parseInt (s_memberid );

?? Description:
?? The above code snippet converts the value of the form field memberid submitted by the user to an integer.

?? Note:
?? If you enter a correct number, such as 1082, there is no problem. However, if the user inputs T1082, because T1082 is not a valid digital format, JAVA cannot convert it into a suitable number, leading to a java. lang. NumberFormatException numeric formatting exception.

?? Solution:
?? When a string is used to convert it to a number, an exception is caught. Exception Handling is performed according to the exception handling method. 1. When an exception is detected, a default value is assigned to a variable; (in some cases, a program error may occur. [for example, if the default value is not handled in other modules, exceptions or errors may occur.]) Follow Exception Handling Method 3: Check that an exception occurs and prompt the user to enter the exception in the correct numeric format. (Implementation is a little troublesome, but the error is blocked before your module [that is, the value you provide to other modules is safe].) Rewrite the program in this way, which is a little effort-consuming during programming, but it does make your module more robust. Rewrite code segment 3 according to the preceding requirements:

?? String s_memberid = request. getParameter ("memberid ");
?? Int I _memberid;
?? Try
?? {
??? I _memberid = Integer. parseInt (s_memberid );
???...
??}
?? Catch (NumberFormatException nfe)
?? {
??? // Method 1: (simple. The default value is 0 ;)
??? I _memberid = 0;
??? // Method 2: (this is a simple method. We recommend that you use a more friendly reminder method)
??? Out. println ("");
??}

?? 3. String out-of-bounds Errors java. lang. StringIndexOutOfBoundsException and other string-related errors

?? Code segment 4:
?? String s_all_power = "1010011 ";
?? String s_access_power = s_all_power.substring (3,4 );

?? Description:
?? The above code snippet function is used to obtain the 4th characters in the string s_all_power.

?? Note:
?? Generally, the program will not be faulty. If s_all_power length becomes short for some reason, the program will throw a string error.

?? Solution:
?? When a string is intercepted (substring, charAt), converted to a byte array (getBytes), and converted to a string (valueOf, check the existence (null or not) and length of the Operation String object before performing the operation.

?? Rewrite to get:

?? String s_all_power = "1010011 ";
?? If (s_all_power.length> 4)
??? String s_access_power = s_all_power.substring (3,4 );

?? 4. The error java. lang. NoClassDefFoundError is not found in the class definition.

?? Cause:
?? The JAVA class file called by this program is not correctly uploaded;

?? Solution:
?? Upload a JAVA file again.

?? JAVA files have been uploaded, but the application server does not detect them. We recommend that you update the JSP page again.

?? Solution:
?? Update and upload the JSP page, or restart the application server.

?? 5. JAVA Errors java. lang. Error

?? Cause:

?? 1. The external resources accessed by the system are not closed, resulting in a large waste of external resources, which may lead to the failure of the system to operate normally;
?? 2. The system has been shut down for too many times to access external resources, and the external system cannot process them properly;
?? 3. Exceptions occurred to external resources accessed by the system.

?? Solution:

?? 1. Before accessing an external resource, check whether the resource (such as a database) can be normally connected or operated.
?? 2. When accessing external resources, if a connection is established, close the operation and only close the operation once.
?? 3. Share external resources in the same operation as much as possible to reduce resource consumption and improve program execution efficiency.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.