Brief analysis of several common errors in Java

Source: Internet
Author: User
Error 1, NULL pointer error java.lang.NullPointerException





uses a basic Java data type, the value of a variable is either already a default value, and if it is not properly assigned, the program cannot compile, thus using the basic Java data type (Double,float,boolean,char,int,long) Typically, null pointer exceptions are not caused. Thus, null pointer anomalies are mainly related to the operation of the object.





below is a list of several scenarios where null pointer exceptions may occur and the corresponding solution:





immediately starts using the object regardless of whether it is empty.


(JSP) code Segment 1:


out.println (Request.getparameter ("username"));


Description:

The function of
code Segment 1 is very simple, which is to output the value of the table field "username" entered by the user.





Description:


looks like the above statement can't find any grammatical errors, and in most cases it's not a problem. However, if a user does not provide a value for the form field "username" when entering data, or bypasses the form's direct input in some way, the value of Request.getparameter ("username") is empty (not an empty string, null object). ), the println method of an Out object cannot operate directly on an empty object, so the JSP page where code Snippet 1 is located will throw a "java.lang.NullPointerException" exception.





even if the object may be empty, some methods such as ToString (), Equals (object obj), and so on, are called for Java.lang.Object or the object itself.


(JSP) code Segment 2:





String userName = Request.getparameter ("UserName");


If (username.equals ("root"))


{....}








Description:

The function of
code Segment 2 is to detect user-supplied user names and to perform special operations if the user name is "root".





Description:


in Code Snippet 2, if a user does not provide a value for the form field "username", the string object is username to a null value and cannot directly compare a null object to another object, likewise, the JSP page where code segment 2 is thrown ( java.lang.NullPointerException) NULL pointer error.





(JSP) code segment 3:


String userName = Session.getattribute ("Session.username"). ToString ();





Description:

The function of
code snippet 3 is to remove the Session.username value from the session and assign the value to the string object UserName.





Description:


in general, if a user has already made a session, there is no problem; however, if the application server restarts and the user has not logged on again, it may be that the user closes the browser but still opens the original page. Then, the value of the session is invalidated, causing the value of the Session.username to be empty. The direct execution of the ToString () operation on a null object causes the system to throw (java.lang.NullPointerException) a null pointer exception.





Solution:


in order to make sure that the object being manipulated or referenced is not empty, if we want to manipulate or reference an object, we first check that the object is instantiated and not empty, and add a process to the system for the object to be empty.





For example, a string object is used to save the result of a user's submission, and when an operation involving an object is detected, if it is empty, and after checking that the object is empty, you can then choose one of the following ways to handle it:





processing 1) to check that the object is empty, set the object value to an empty string or a default value;


processing 2) detects that an object is empty, does not perform an operation at all, and jumps directly into other processing.


processing 3) to check that the object is empty, prompt the user to operate with errors.


Code Snippet 2 in the above way to rewrite, get:


Mode 1:





String userName = Request.getparameter ("UserName");


//When the variable value is empty, it is converted to the default empty string


If (userName = null)


userName = "";


If (username.equals ("root"))


{..........}








Mode 2:





String userName = Request.getparameter ("UserName");


//When the variable value is empty, converts to the default empty string and does not perform the operation.


If (usrename!= null)


{


If (username.equals ("root"))


{..........}


}

















Mode 3:





String userName = Request.getparameter ("UserName");


//When the variable value is empty, converts to the default empty string and does not perform the operation.


If (usrename = null)


{


//Prompts user to enter information as empty


}

















in practice, the above three processing methods also apply to other exception handling:





exception handling 1) Check for exception occurrence, set object value to an empty string or a default value;


exception Handling Mode 2 detects an exception, does not perform an operation at all, and jumps directly into other processing.


exception handling 3) Check the exception to appear, prompting the user to operate with errors.





2. Format Digital Error java.lang.NumberFormatException analysis


(JSP) code segment 3:





String S_memberid = Request.getparameter ("MemberID");


int i_memberid = Integer.parseint (S_memberid);


Description:


The preceding code snippet converts the value of a user-submitted form field MemberID to an integer.





Description:


If the user enters the correct number such as: 1082, there will be no problem. However, if the user enters T1082, because T1082 is not a valid number format, Java cannot convert it to an appropriate number, causing the java.lang.NumberFormatException number to be thrown in an abnormal format.





Solution:


When a string is converted to a number, catch exceptions, handle exception handling by exception 1: Check for exception occurrence, assign to a variable a default value (may in some cases cause a other program error [for example, the other module does not handle the default value you give, May cause some exceptions or errors to occur. ) by exception handling 3: Check the exception to occur, prompting the user to use the correct number format input. (Implementation is a bit cumbersome, but blocking the error before your module [that is, the value you provided to the other modules is safe].) To rewrite the program in this way, it's a bit cumbersome to program, but it does make your module more robust. Rewrite the code snippet 3 according to the above requirements and get:





String S_memberid = Request.getparameter ("MemberID");


int I_memberid;


Try


{


I_memberid = Integer.parseint (S_memberid);


...


}


catch (NumberFormatException nfe)


{


//Mode 1: (Simple, directly to the number for a default value of 0;)


I_memberid = 0;


//Mode 2: (very humble practice, suggest a more friendly way of prompting)


out.println (' <script>alert (' The user number you provided is incorrect, please re-enter it. '; History.go ( -1);</script> ");


}





3, string-like error java.lang.StringIndexOutOfBoundsException string class related error


Code Segment 4:





String s_all_power = "1010011";


String s_access_power = s_all_power.substring (3,4);





Description:

The function of
above code snippets is to get the 4th character in the string s_all_power.





Description:


in general, the program will not have problems, if for some reason, the length of the s_all_power is shortened, the program will throw a string error.





solution: To intercept a string (substring, charAt), convert to a byte array (getBytes), convert a character array to a string (valueof) operation, first check the existence of the action string object (whether it is empty) and the length of the operation.





rewrite get:





String s_all_power = "1010011";


if (s_all_power.length>4)


String s_access_power = s_all_power.substring (3,4);





4. The class definition did not find the error java.lang.NoClassDefFoundError


Reason:





because the Java class file that the program calls to is not uploaded correctly;


Solution:


to upload the Java class file again.





Java class file has been uploaded, but the application server is not detected, it is recommended to update the JSP page.


Solution:


the JSP page to update and upload it, or reboot the application server.





5,java Error Java.lang.Error





Reason:





1. For the system access to external resources, did not perform shutdown operation, resulting in a large amount of waste of external resources, may eventually lead to the system will not function properly;


2. The number of external resources accessed by the system has been closed too many times, and the external system cannot handle it properly;


3. The external resources accessed by the system are abnormal.


Solution:





1. Before accessing an external resource, first check to see if the resource, such as the database, is properly connected or operated.


2. When you access an external resource, you must close the operation and do a shutdown only once if you are connected.


3. As far as possible in the same operation to share external resources, to reduce the operation of resources consumption, improve the efficiency of program execution.








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.