On the null-pointer anomaly _java of Java exception handling

Source: Internet
Author: User
Tags constant exception handling finally block throw exception

Listen to the teacher said, in the later study most of the anomalies are null pointer anomalies. So take a little time to play the game to check what is a null pointer exception

One: The main causes of NULL pointer anomalies are as follows:

(1) When an object does not exist and then call its method will produce an exception obj.method ()//obj object does not exist

(2) An exception is generated when accessing or modifying a field that does not exist for an object Obj.method ()//method methods do not exist

(3) The string variable is not initialized;

(4) An object of an interface type is not initialized with a specific class, such as:

List lt;
List lt = new ArrayList (); it won't be an error.

When an object's value is empty, you are not judged to be empty. You can try adding one line of code to the following code:

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

Change into:

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

Null pointer solution:

Focus on the row where the error occurred, through the null pointer anomaly generated two main reasons to diagnose specific errors. 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 anomalies:

(1) NULL pointer error Java.lang.NullPointerException

There are 8 basic data types in Java, the value of a variable can have its default value, add no normal assignment to it, and the Java Virtual machine is not compiled correctly, so using a basic Java data type does not normally cause null pointer exceptions. In actual development, most of the null pointer anomalies are mainly related to the operation of the object.

Ii. Java exception handling mechanism

There are two ways to handle code that might appear to be abnormal:

First, in the method to catch and handle the exception with the Try...catch statement, the Catach statement can have multiple, to match multiple exceptions. For example:

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

Second, for exceptions that cannot be handled or to be transformed, 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 is simply throwing an exception, in a multi-tiered nested call to the method invocation method, the Java virtual opportunity will look back from the method code block where the exception occurred, until the code block that handled the exception is found. The exception is then handed over to the appropriate catch statement for processing. If the Java Virtual Machine traces 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 are followed:

First, the Printstacktrace () method of the object that invokes the exception, printing the exception information for the method call stack.

Second, if the thread that has the exception is the primary, the entire program terminates, and if the thread is not the main, the other thread continues to run.

Through the analysis of thinking, we can see that the earlier processing of abnormal consumption of resources and time, the impact of the scope of the smaller. Therefore, do not throw the exception that you can handle to the caller.

It is also important not to overlook the code that must be executed in any case by a finally statement, which ensures that some of the code's reliability must be executed in any case. For example, when a database query is abnormal, you should release the JDBC connection, and so on. The finally statement executes before the return statement, regardless of its position, or whether an exception is found in a try block. Finally, the only thing that is not executed is that the method executes the System.exit () method. The role of System.exit () is to terminate the currently running Java Virtual machine. Finally, it is not possible to change the return value by assigning a new value to a variable, and it is also recommended that you do not use returning statements in a finally block, which makes no sense 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, and catch, finally, can be composed

Try...catch...finally, Try...catch, try...finally three structures, catch statements can have one or more, finally statements up to one, try, catch, finally None of these three keywords can be used alone.

second,try, catch, finally three blocks in the scope of the variables are independent and cannot access each other. If you want to be accessible in three blocks, you need to define the variables outside the blocks.

third, multiple catch blocks, when the Java virtual opportunity matches one of the exception classes or its subclasses, executes the catch block without executing another catch block.

Four,throw statements are not allowed to follow other statements, because these do not have the opportunity to execute.

Fifth, if a method calls another method that declares an exception, the method either handles the exception or the declaration throws.

The difference between 2.2throw and throws keywords:

Throw is used to throw an exception in the method body. The syntax format is: Throw exception object.

Throws is used to declare what exceptions the method might throw, and after the method name, the syntax format is:

Throws exception type 1, exception type 2 ... Exception type N.

Three: The following lists several scenarios where null pointer exceptions may occur and the corresponding solution:

Code Snippet 1:

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

Analysis: The function of code Segment 1 is very simple, is the output user input "username" value.

Description: It seems that the above statement cannot find any grammatical errors, and in most cases is not a problem. However, if a user does not provide a value for the form field "username" when entering data, or bypasses form direct input in some way, the value of this request.getparameter ("username") is null (note that it is not an empty string and null. , the println method of an Out object cannot be directly manipulated on an empty object, so the JSP page where code Snippet 1 is located will throw a "Java.lang.NullPointerException" exception. And even if the object may be empty, some of the methods such as ToString (), equal (object obj), and so on, are invoked for Java.lang.Object or the object itself.

Code Snippet 2:

String userName = Request.getparameter ("UserName"); 
If (username.equals ("root")) 
{...} 

Analysis: The function of code Snippet 2 is to detect user-supplied user names and to perform 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 to a null value and cannot directly compare a null object to another object. The JSP page where code snippet 2 is located throws a null pointer error.

a tip: If you want to compare the return value of a method with a constant, put a constant in front of it, you can avoid calling the Equals method of the null object. Such as:

If ("root". Equals (UserName)) 
{...} 

Even if the Username object returns a null object, there will be no null pointer exception and it can function as usual.

Code Snippet 3:

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

Analysis: 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.

Note: in general, if a user has already made a session, there is no problem, but 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 a null-pointer exception.

Code Snippet 4:

public static void Main (String args[]) {person 

p=null; 

P.setname ("John"); 

System.out.println (P.getname ()); 

Analysis: declares a person object and prints out the name in the object.

Description: This time your p will appear null pointer exception, because you just declared that the person type object and did not create an object, so its heap has no address reference, do not want to use the object to drop the method when you must create objects.

A: Use it directly regardless of whether the object is empty.

(JSP) Code Snippet 1:

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

Analysis: The function of code Segment 1 is very simple, is the output user input "username" value.

Description: It seems that the above statement cannot find any grammatical errors, and in most cases is not a problem. However, if a user does not provide a value for the form field "username" when entering data, or bypasses form direct input in some way, the value of this request.getparameter ("username") is null (note that it is not an empty string and null. , the println method of an Out object cannot be directly manipulated on an empty object, so the JSP page where code Snippet 1 is located will throw a "Java.lang.NullPointerException" exception. And even if the object may be empty, some of the methods such as ToString (), equal (object obj), and so on, are invoked for Java.lang.Object or the object itself.

(JSP) Code Snippet 2:

String userName = Request.getparameter ("UserName");
If (username.equals ("root"))
{...}

Analysis: The function of code Snippet 2 is to detect user-supplied user names and to perform 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 to a null value and cannot directly compare a null object to another object, and likewise, the JSP page where code segment 2 is thrown ( Java.lang.NullPointerException) NULL pointer error.

(JSP) Code Snippet 3:

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

Analysis: 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.

Note: in general, if a user has already made a session, there is no problem, but 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.

The above is a small series for everyone to talk about Java exception handling null pointer exception all content, I hope we support cloud Habitat Community ~

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.