About Java exception handling mechanism in-depth understanding of

Abnormal Profile

In a program, the programmer errors may occur in unexpected circumstances or environment outside the controllable range of the programmer, for example, bad data user, trying to open a file does not exist, and the like. In order to be able to handle run-time errors in a timely and effective program, Java introduces a special exception class.

Example 1

To better understand what is abnormal, the following look at a very simple Java program. The following example code allowing a user to input an integer of 1 to 3, or less, otherwise an error prompts.

package ch11;
import Java.util.Scanner;
public class TestO1
{
    public static void main(String[] args)
    {
        System.out.println("请输入您的选择:(1~3 之间的整数)");
        Scanner input=new Scanner(System.in);
        int num=input.nextInt();
        switch(num)
        {
            case 1:
                System.out.println("one");
                break;
            case 2:
                System.out.println("two");
                break;
            case 3:
                System.out.println("three");
                break;
            default:
                System.out.println("error");
                break;
        }
    }
}

Under normal circumstances, the user may enter a number between 1 to 3 according to the system prompts. However, if the user is not required to input, such as entering a letter "a", then the program at runtime exception will occur, the results shown below.

Please enter your choice: (3 ~ integer between 1)
A
Exception in the Thread "main" java.util.InputMismatchException
AT java.util.Scanner.throwFor (Unknown Source)
AT java.util.Scanner.next (Unknown Source )
AT java.util.Scanner.nextInt (Unknown Source)
AT java.util.Scanner.nextInt (Unknown Source)
AT text.text.main (text.java:11)

The use of reason and the principles of the abnormal condition occurred

An exception is generated in Java, mainly in the following three reasons:
1.Java inner exception error occurs, the exception generated by the Java virtual machine.
2. The program code written exception errors arising from, for example, a null pointer exception, abnormal array bounds. This anomaly is called abnormal unchecked, generally need to focus to handle them in some classes.
3. generated by manual throw statement abnormality, such abnormality called abnormality check, typically used to inform the caller of the method of the necessary information.


Java object-oriented methods to handle the exception. During operation of a method, if an abnormality has occurred, then the method will generate an object representative of the exception, and sent it to the runtime system, the system looks for the appropriate code to handle the runtime exception.

We generate an exception object and submit it to the runtime system is called throw (throw) exception. The system looks at run-time call stack method, able to handle exceptions until you find the type of object, which is a process known as capture (catch) exceptions.

Java exception forces the user to consider the robustness and security of the program. Exception handling should not be used to control the normal flow of the program, its main role is to capture a program exception occurs during operation and corresponding processing. Write code to handle exceptions a method that may arise, can follow the following three principles:
1. Use the try catch statement to catch the exception in the current method declaration.
2. a method is covered, covering it the same method must throw an exception or exception subclass.
3. If a plurality of parent class exception is thrown, the throw method must cover a subset of those unusual and can not throw new exception.

Exception Type

 In Java exception types are all built subclasses of class java.lang.Throwable class, that is located on top of the hierarchy of the Throwable exception class. Two hook and Error Exception class Throwable lower, as shown in FIG.

FIG 1 FIG structural abnormalities

Can be known from FIG. 2, Throwable class is the superclass of exceptions and errors, and the following Error Exception has two subclasses represent errors and exceptions. In which abnormal and non-runtime exceptions, these two anomalies are very different exception classes Exception divided into operation, also known as no abnormalities (Unchecked Exception) and abnormalities (Checked Exception).

  • Exception class for exceptions user program may appear, it is also used to create a custom class exception type class.
  • Error is defined in the usual environment program not want to be captured exception. Error type of exception for the runtime system itself related to the Java runtime error is displayed by the system. Stack Overflow is an example of such an error.
  • This chapter does not discuss about Error type of exception handling, because they are usually catastrophic fatal error, the program can not control. The contents of this chapter will discuss the type of exception handling Exception.

Exceptions are RuntimeException exception class and its subclasses, such as NullPointerException, IndexOutOfBoundsException other runtime, these anomalies are not checked exception, capturing processing program may be selected, or may not handle. These abnormalities typically caused by a logic error, the program should be avoided as much as possible from a logical point of such an abnormality occurs.

Refers to an abnormal abnormality other than the non-operating time RuntimeException, it belongs to the class and its subclasses Exception type. From a linguistic point of view the program is an exception must be handled, if not addressed, the program will not compile. As IOException, ClassNotFoundException Exception and other user-defined exception, no custom abnormalities in general. Table 1 lists some of the common types of exceptions and their role.

Table 1 Java exception type in common
Exception Type Explanation
Exception Root exception class hierarchy
RuntimeException Exceptions, most of the java.lang abnormal root class runtime
ArithmeticException Arithmetic error spectrum disorders such as division by zero
ArraylndexOutOfBoundException Array size is less than or greater than the actual size of the array
NullPointerException Attempts to access null object members, null pointer exception
ClassNotFoundException You can not load the required classes
NumberF ormatException Digital format conversion abnormality, such as string to float invalid digital conversion
IOException I / O exception root class
F ileN otF oundException File Not Found
EOFException End of File
InterruptedException Thread interrupts
IllegalArgumentException The method of receiving an illegal parameter
ClassCastException Abnormal type conversion
SQLException Abnormal operation of the database

In java applications, there are two exception handling mechanism: throw exceptions, catch exceptions.

Declare an exception thrown:

  When a method throws an exception error occurs, the delivery method creates an exception object system is running, the exception object contains the exception type and program abnormal state such as abnormal information. The runtime system is responsible for finding and disposal of abnormal code execution.

  The method can declare an exception to be thrown in the way by keyword throws, then an exception is thrown by throw objects inside the method. This section details how to declare an exception and throw exceptions in Java.

Several differences between throws and throw keywords on the keywords used are as follows:

  • All information is used to declare an exception throws a method may throw, throw it refers to a specific type of exception thrown.
  • Typically by the method throws declaration (s) may be thrown exception information in a process (class) of the declaration, the declaration and the internal through a throw exception information specific method (s).
  • throws usually not explicitly catch the exception, by the system will automatically capture all the anomalies thrown superior method; throw it require the user to capture relevant exceptions, and then its related packaging, and finally the exception information after the packaging thrown.

statement throws an exception

   When an abnormality occurs a method of treatment it is not, then declare the exception of the head of the process, in order to pass the exception of the method of processing to the outside. You throw an exception can be used in the key head declaration method, which has the following format:

returnType method_name(paramList) throws Exception 1,Exception2,…{…}

Wherein, returnType represents the type of the return value, method_name name representation, Exception 1, Exception2, ... represents exception class. If there are multiple exception classes, separated by commas. These exception classes may be called the method will throw an exception is generated, the body may be a method for generating and thrown.

Example 1

Create a readFile () method, which is used to read the contents of the file, in the process of reading may produce an IOException, but without any treatment in this method, an exception to the caller and the process may occur . Try catch to catch exceptions using the main () method, and outputs the abnormality information. code show as below:

a java.io.FileInputStream Import;
Import java.io.IOException;
public class Test04
{
    public void readFile () throws IOException
    {
        // the method declaration defines exception
        FileInputStream file = new FileInputStream ( "read.txt "); // record of FileInputStream instance object
        int F;
        the while ((F = File.read ()) = -. 1!)
        {
            System.out.println ((char) F);
            F = File.read ();
        }
        File.close ();
    }
    public static void main (String [] args)
    {
        Throws By Test04 new new = T ();
        the try
        {
            t.readFile (); // call readFHe () method
        }
        the catch (IOException E)
        {// catch exception
            System.out.println (E);
        }
    }
}

The above code, first used in the definition of readFile when () method throws an exception keyword statement that may arise in the process, and then call readFile () method main () method, and use the catch statement to catch exceptions generated.

Note: When writing the code class inheritance to be noted that, when the cover subclass the parent with a method throws clause, subclass method declaration throws clause is not the parent class of the corresponding method throws clause occurs no exception types Therefore throws clause can restrict the behavior of the subclass. In other words, the subclass method throws the exception does not exceed the scope of the parent class definition.

throw an exception is thrown

throw statement used to directly throw an exception, followed by a thrown exception class objects, syntax is as follows:

throw ExceptionObject;

Wherein, ExceptionObject must be an object class or subclass of Throwable. If a custom exception class Throwable must also be direct or indirect subclass. For example, the following statement will produce syntax errors at compile time:

1.throw new String ( "thrown"); // because String class is not a subclass of class Throwable

When the throw statement is executed, it will not execute the following statements, then the program branches to the caller program, to find matched catch phrase, executes the corresponding exception handler. If the matching catch clause is found, the program calls up sub-layer. Thus up layer by layer, until the outermost exception handler terminates the program and print a case where the call stack.

Example 2

In a warehouse management system, required by the user name of the administrator needs more than eight letters or numbers, can not contain other characters. When the length of 8 bits or less thrown exception, and displays the abnormality information; when the character containing the non-letters or numbers, the same exception is thrown, the display abnormality information. code show as below:

java.util.Scanner Import;
public class for TEST05
{
    public Boolean validateUserName (String username)
    {
        Boolean = CON to false;
        IF (username.length ()>. 8)
        {// if the username length is greater than 8 bits
            for (int i = 0; I <username.length (); I ++)
            {
                char CH = username.charAt (I); // Get every character
                if ((ch> = '0 ' && ch <= '9') || (ch > = 'A' && CH <= 'Z') || (CH> = 'A' && CH <= 'the Z'))
                {
                    CON = to true;
                }
                the else
                {
                    CON = to false;
                    throw new IllegalArgumentException ( "User name can only consist of letters and numbers! '");
                }
            }
        }
        The else
        {
            the throw new new an IllegalArgumentException ( "username must be greater than 8!");
        }
        Return CON;
    }
    public static void main (String [] args)
    {
        for TEST05 TE = new new for TEST05 ();
        Scanner INPUT = new new Scanner (the System.in);
        System.out.println ( "Please enter your name:");
        String username = input.next ();
        the try
        {
            Boolean te.validateUserName = CON (username);
            IF (CON)
            {
                the System.out .println ( "enter the correct user name!");
            }
        }
        catch(IllegalArgumentException e)
        {
            System.out.println(e);
        }
    }
}

As the above code, the validateUserName () method throws an IllegalArgumentException exception of two, i.e. when a user name or a numeric character and non-alpha containing less than 8 bits length. In the main () method, call the validateUserName () method, and use the catch phrase to capture this method may throw an exception.

Running the program, when the user name of the user input comprises a non-numeric letters or characters, the program outputs an abnormality, as shown below.

Please enter your user name:
Administrator @ #
java.lang.IllegalArgumentException: user name can only consist of letters and numbers!

When the user inputs a user name length is less than 8 bits, the program will output the same abnormality, as shown below.

Please enter your user name:
ADMIN
java.lang.IllegalArgumentException: Username length must be greater than eight!

Catch exceptions:

  After method throws an exception, the runtime system will be converted to find suitable exception handler. Potential remaining exception handler is sequentially stored in the call stack method is set when an exception occurs. When a match type of abnormality and method of abnormality type of exception thrown processor can handle, i.e. the appropriate exception handler. When the system is running from the start of the methods abnormal, turn back to check the method call stack, until a suitable method to find and execute the exception handler. When the runtime system traversing the call stack without finding an appropriate exception handler method, runtime system is terminated, also means java program terminates.

Usually try, catch, finally catch exceptions:

the try
{
    logic block
}
the catch (ExceptionType E)
{
    exception handling code block
}
the finally
{
    cleanup code
}

try block: for capturing exception. Thereafter be zero or more catch blocks, if there is no catch block, it must be followed by a finally block.

catch block: a process to try to capture the exception.

finally block: whether to capture or handle exceptions, finally block will be executed in a statement. When encountering a return statement in the try block or catch block, finally statement block will be executed before the method returns.

In the following four special cases, finally block is not executed:

1) an abnormality occurs in the finally block.

2) in the preceding code with the System. Exit (exit the program.

3) threaded programs where the death.

4) Close the CPU.

Execution order try, catch, finally statement block:

1) When not try to capture exception: try statement statement blocks are executed one by one, the program will skip the catch block, and finally block execute subsequent statements;

2) When the abnormality try to capture, there is no catch block this abnormality processing: When abnormality in the try block of a statement appears without processing this exception catch block, this exception will be thrown to the JVM treatment, the statement in the finally block will still be executed, but the statement after the finally block will not be executed;

3) When try to capture the exception, the catch block to handle this situation there exception: in the try block is performed in the order, when a statement is executed to a certain abnormality occurs, the program will jump to the catch block, and the match is the catch block, to find the corresponding processing program, the other catch block will not be executed, the try block, an abnormality occurs after the statement is not executed, executed after the catch block, finally block execute in the statement, and finally execute the statement after the finally block.

 

 

 

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159798.htm