Basics of JAVA--Exceptions and Handling Methods

In java programming, exception objects are derived from an instance of the Throwable class.

exception architecture

exception hierarchy in java

Throwable system:

  • Error : Serious error Error, an error that cannot be handled, can only be avoided in advance, like a terminal illness.
  • Exception : Indicates an exception. After an exception occurs, the programmer can correct it by means of code, so that the program can continue to run, which must be dealt with. Like a cold or appendicitis.

Exception system:

  • IOException: We need to deal with exceptions in the compiler phase, such as date formatting errors and file locations not found.
  • RuntimeException: JVM will automatically handle exceptions during runtime, such as array subscript out of bounds.

exception handling method

RuntimeException

This kind of exception does not need to be handled by us personally, the JVM will detect the exception and handle it. The processing method: detect the exception –> print the exception information on the console –> interrupt the running of the program.
That is to say, the JVM will directly print the error on the console, and note that subsequent programs after the error will not be executed .
Of course, we also judge whether the exception exists by ourselves, and then use the capture method to handle it (in this way, subsequent programs will be executed).

throw throws an exception

It can be used to detect whether the data is safe or not, and manually handle exceptions during runtime.

public static void main(String[] args) {
    
    
//      int arr[] = new int[]{1,2,3};
        int arr[] = null;
        int temp = getArr(arr,3);
        System.out.println("temp="+ temp);
    }

    public static int getArr(int[] array, int index) {
    
    

        if (array == null) {
    
    
            throw new NullPointerException("空数组");
        }
        int length = array.length;
        if (index > length-1) {
    
    
            throw new ArrayIndexOutOfBoundsException("超出数组下标");
        }
        return array[index];
    }

insert image description here

IOException

The exception in the compiler needs to be handled by ourselves, otherwise it will always report an error and fail to compile, and the compiler will remind us of the exception.

thorws statement exception

Declaring an exception will throw the compiler exception to the caller who calls the method, and the caller must also declare the exception until it is thrown to the main function, and then declare the exception and throw it to the JVM for processing.
If there is an inheritance relationship in multiple declared exceptions, you can only declare the parent class exception. The easiest way is to directly declare Exception.

public static void main(String[] args) throws IOException{
    
    
            readFile("c://b.tx");
    }

public static void readFile(String fileName) throws IOException{
    
    
        if(!fileName.endsWith("txt")) {
    
    
            throw new IOException("文件类型不对!");
        }

        if(!fileName.equals("c://b.txt")) {
    
    
            throw new FileNotFoundException("文件路径不对");
        }
        System.out.println("文件读取成功!");
    }

try catch catch exception

The follow-up program of the exception handled in this way will be executed normally, and the follow-up program of the exception in try will not be executed, that is, the program included in the try curly braces, but the follow-up program will be executed normally.

public static void main(String[] args){
    
    
        // 使用try catch来处理异常

        try {
    
    
            readFile("c://b.tx");
        } catch (IOException e) {
    
    // 抛出什么异常,就定义什么异常
            // 打印异常全面信息,属于超类Throwable的方法
            e.printStackTrace();
        }
        System.out.println("后续程序");
    }

    /*
    * FileNotFoundException为编译期异常需要我们亲自处理,使用throws抛出给方法调用者直至
    * 抛到主函数,再抛给JVM处理。
    * IOException问所有编译期异常的父类,可以只抛出该类,其他的异常就被包括了。
    * */
    public static void readFile(String fileName) throws IOException{
    
    
        if(!fileName.endsWith("txt")) {
    
    
            throw new IOException("文件类型不对!");
        }

        if(!fileName.equals("c://b.txt")) {
    
    
            throw new FileNotFoundException("文件路径不对");
        }
        System.out.println("文件读取成功!");
    }

insert image description here

finally keyword
The code block in this keyword will be executed regardless of whether an exception occurs or no exception occurs, and is usually used to release resources.

public static void main(String[] args){
    
    
        // 使用try catch来处理异常
        try {
    
    
            readFile("c://b.txt");
        } catch (IOException e) {
    
    // 抛出什么异常,就定义什么异常
            // 打印异常全面信息,属于超类Throwable的方法
            e.printStackTrace();
        } finally {
    
    
            // finally中的方法,无论异常出现与否都会执行
            // 注意事项:finally中避免出现return方法,否则会一直返回该值
            System.out.println("资源释放");
        }
        System.out.println("后续程序");
    }

    public static void readFile(String fileName) throws IOException {
    
    
        if(!fileName.endsWith("txt")) {
    
    
            throw new IOException("文件类型不对!");
        }

        if(!fileName.equals("c://b.txt")) {
    
    
            throw new FileNotFoundException("文件路径不对");
        }
        System.out.println("文件读取成功!");
    }

insert image description here

Handle multiple exception methods

A method to handle multiple exceptions:

  • One: One exception and one processing is to write multiple try catches, which is too troublesome and not advisable
  • Two: Multiple exceptions, multiple processing, write a try to catch all exceptions, write multiple catches to handle exceptions of different types.
    Note: If there is an inheritance relationship between two exceptions, you can only write the parent class and not the subclass. If you have to write both, then the subclass catch must be written on the parent class, otherwise an error will be reported (reason: subclass exceptions can be passed through multiple The state method is assigned to the parent class, and the subclass is redundant below.)
  • Three: One-time processing of multiple exceptions: one try and one catch, Exception can be used in catch to handle all exceptions.

Child parent class method exception

The parent class method throws multiple exceptions, and the subclass also throws these exceptions when rewriting the method, or throws a subclass of these exceptions, or does not throw an exception.
The method of the parent class does not throw an exception, and the subclass cannot throw an exception, it can only be handled by capturing.
Summary: How the parent class handles the exception and the subclass handles it.

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/108933417