Road java learning: 29 Exception Handling

Here Insert Picture Description

I. Overview abnormalities

After learning Java, the compiler often encounter, suggesting abnormal, abnormal when an event occurs during the execution of the program, it interrupts the normal program instruction being executed stream.
For example the following code:

public class Exceptiontest {
    public static void main(String[] args) {
        int num=3/0; 
        System.out.println(num); 
    }
}

The results suggest that abnormal operation of arithmetic:
Here Insert Picture Description
the program is running exception occurs, the system does not execute down, ahead of the end, this is the exception.
Java is an object-oriented programming language, therefore, is a form of abnormal instance of the class occurs in the Java language. When an error occurs in a method, this method will create an object, and passes it to a running system, this object is the exception object. Exception handling mechanism, the main logic program code in an irregular situation may be separated, i.e. in the main flow while writing code in the exception process other methods.
Common exceptions are as follows.

II. Common exceptions

Exception class Explanation
ClassCastException Abnormal type conversion
ClassNotFoundException I did not find the appropriate category abnormalities
ArithmeticException Arithmetic exception
ArrayIndexOutOfBoundsException Cross-border abnormal array subscript
ArrayStoreException The array contains incompatible Throws exception
SQLException Abnormal operation of the database class
NullPointerException Null pointer exception
NoSuchFieldException Field is not abnormal to find
NoSuchMethodException The method does not throw exceptions found
NumberFormatException String conversion to numbers thrown an exception
NegativeArraySizeException The number of array elements is negative exceptions thrown
StringIndexOutOfBoundsException String index out of range exception thrown
IOException Abnormal input and output
IllegalAccessException Not allow access to certain types of abnormal
InstantiationException When an application tries to use in class Class newInstance () method creates an instance of a class, but the specified class object can not be instantiated Thrown.
EOFException End of file abnormal
FileNotFoundException File not found abnormalities

III. Catch an Exception

Java language exception trapping structure consists of three parts try, catch, finally, wherein the try block is stored in the Java language exception may occur, the catch block after the try block, used to excite the captured exception, the finally block is the last statement executed exception handling part structure, regardless of how the try statement block exit code will be executed finally block, the exception handler is roughly divided into blocks of statements and try-catch finally block.

1. try-catch block of statements

The code is slightly changes:

public class Exceptiontest {
    public static void main(String[] args) {
        int num=3/0; 
        System.out.println(num); 
        System.out.println("继续运行"); 
    }
}

Running shows, once the abnormal termination would appear to run.
Here Insert Picture Description
After the addition of the exception handling block tyr-catch statement:

public class Exceptiontest { 
    public static void main(String[] args) {
    try {
        int num=3/0; 
        System.out.println(num); 
        }catch(Exception e) {
            e.printStackTrace();
        }     
    System.out.println("继续运行"); 
    }
}

The results can be seen running, the program still output the last message, not because of abnormal termination.
Here Insert Picture Description

Exception是try代码块传递给catch代码块的变量类型,e是变量名,catch代码块中的语句“e.printStackTrace()方法用于指出异常的类型,性质,栈层次已经出现在程序中的位置。”另外两个方法如下:
getMessage() : 输出错误性质
toString() : 给出异常的类型与性质。

2.finally statement block

Full exception handling finally statement statement must contain, regardless of presence or absence of a program exception occurs, and try-catch block of statements between whether the order is finished, finally statement will be executed.
In the following four special cases, finally block is not executed:

在finally语句中发生了异常
在前面的代码中使用了System.exit()退出程序
程序所在的线程死亡
关闭CPU

IV. Custom exception

In addition to the built-in exception classes, users can also customize exceptions, only need to inherit Exception class can be.
Proceed as follows:
1. Create custom exception class.
2. In the method throws an exception object throw keyword.

3. If the current processing method throws an exception of exceptions, you can use the try-catch block to catch and statement processing, or by keyword throws an exception to be thrown to the methods specified in the declaration at the caller method, continue to the next step operating.

4. catch and handle the exception in the caller's abnormal.

E.g:

//创建自定义异常类
class MyException extends Exception{
    public MyException(String ErrorMessage) {
    super(ErrorMessage); 
    }
}

//在方法中通过throw关键字抛出异常对象

public class Exceptiontest {
    static int avg(int number1,int number2) throws MyException{
    if (number1 < 0 || number2 < 0) {
        throw new MyException("不可以使用负数"); 
    }
    if (number1 > 100 || number2 > 100) {
        throw new MyException("数值太大了"); 
    }
    return (number1 + number2); 
    }
    public static void main(String[] args) {
        try {
            int num =avg(155,155); 
            System.out.print(num); 
        }catch(MyException e) {
         System.out.println(e);
        } 
    }
}

operation result:
Here Insert Picture Description

V. thrown in the method

1. Use keyword throws an exception is thrown

When throws keyword usually applied in the method declaration to specify a method that may be thrown, the plurality of abnormalities can be separated by commas.
Such as:

int avg(int number1,int number2) throws MyException{
//   。。。。。。
}

使用throws关键字将异常抛给上一级后,如果不想处理该异常,可以继续向上抛出,但最终要有能够处理该异常的代码。

2. Use the keyword throw throw an exception

throw keyword commonly used in the method body, and throws an exception object. Program to terminate immediately the implementation of a throw statement, the statement is not behind him executed. After the throw by throwing an exception, if you want to in the previous code to capture and handle exceptions, you need to use the method throws an exception in the throws keyword named to the exception thrown in a statement of the method , if you want to catch throw throw an exception, you must use the try-catch block.
Such as:

if (number1 < 0 || number2 < 0) {
         throw new MyException("不可以使用负数"); 
     }

If wrong, please correct me criticism, welcome criticism.
Each text sentence: life can not wait for someone else to organize, to struggle and to fight for their own; regardless of the result is a tragedy, but consolation is that you always live a worthwhile in this world. - Lu Yao, "Ordinary World"

Published 74 original articles · won praise 180 · views 30000 +

Guess you like

Origin blog.csdn.net/Fdog_/article/details/104747293