Simple Principle and Application of Exception Handling Mechanism in Java

Source: Internet
Author: User

Exceptions are exceptions or errors that occur when Java programs are running (not compiled). They are similar to events in real life, events in real life can contain information such as the time, location, character, and plot of an event. They can be represented by an object. Java uses an object-oriented method to handle exceptions, it encapsulates every exception in the program into an object, which contains the exception information.

Java classifies exceptions. Different types of exceptions are represented by different Java classes. The root classes of all exceptions are Java. Lang. throwable. The following two subclasses are derived from throwable:Error and exception, Error indicates that the application itself cannot overcome and recover a serious problem. The program only has dead parts, for example, memory overflow, thread deadlock, and other system problems. Exception indicates that the program can also overcome and recover the problems, including system exceptions and Common exceptions. system exceptions are caused by Software defects, that is to say, software developers cannot overcome and restore the problems caused by weeks of consideration. However, in this case, the software system can continue to run or let the software die. For example,Array script out of bounds (arrayindexoutofboundsexception), null pointer exception (nullpointerexception), Class conversion exception (classcastexception );Normal exceptions are caused by changes in the operating environment or exceptions. They are problems that users can overcome, such as network disconnection and insufficient disk space, the program should not die.

Java provides different solutions for system exceptions and Common exceptions. The Compiler forces normal exceptions to try .. catch processing or throws declaration is used to continue to be thrown to the upper-layer call method for processing. Therefore, common exceptions are also called checked exceptions, and system exceptions can be handled or not processed. Therefore, the compiler does not force try .. catch or throws are used for processing. Therefore, a system exception is also called an unchecked exception.

  • Nullpointerexception
Null Pointer Error Java. lang. nullpointerexception uses the Basic Java data type. The value of the variable is either the default value. If no value is assigned to the variable, the program cannot compile the variable. 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 code segment 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, no problem occurs. 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 (), are called (),
Equals (Object obj.

(JSP) code Segment 2: String userName = request. getParameter ("username ");

If (userName. equals ("root ")){....}

Description: The function of code snippet 2 is to check the user name provided by the user. If the user name is "root", perform some special operations.
Note: In code segment 2, if a user does not provide a value for the form field "username", the string object userName is null, A null object 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 code snippet 3 is to retrieve 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 occurs. However, if the application server is restarted 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:

In practice, the above three methods also apply to the handling of other exceptions:
Exception Handling Method1) Check whether an exception occurs. Set the object value to an empty string or a default value;
2) if an exception is detected and no operation is executed, the system jumps to another process.
3) Check whether an exception occurs and prompt the user for an operation error.

 

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.