Java exception handling

Keywords: Java network jvm Programming

1, Exception overview and exception architecture

1. Overview of exceptions

In the process of using computer language for project development, even if the programmer writes the code perfectly, there are still some problems in the operation of the system, because many problems can not be avoided by the code, such as: the format of customer input data, the existence of read-out files, whether the network is always smooth and so on.

1.1 definition of exceptions

In the Java language, the abnormal situation in the execution of a program is called "exception". (syntax and logic errors during development are not exceptions)

1.2 classification of anomalies

Error: a serious problem that the Java virtual machine cannot solve. Such as: JVM system internal error, resource exhaustion and other serious situations. For example: StackOverflowError and OOM. Generally, targeted code is not written for processing.
Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example:
> null pointer access
> trying to read a file that does not exist
> lost network connection
> array corner out of bounds

1.3 description

The best time to catch exceptions is at compile time, but some exceptions can only be found at run time. For example: the array corner is out of bounds and divisor is 0.

2. Exception architecture

 * java.lang.Throwable
 *------ java.lang.Error: generally, targeted code is not written for processing.
 *------ java.lang.Exception: exception handling
 *------ compile time exception (checked)
 *                     |-----IOException
 *                         |-----FileNotFoundException
 *                     |-----ClassNotFoundException
 *------ unchecked, runtimeException
 *                     |-----NullPointerException
 *                     |-----ArrayIndexOutOfBoundsException
 *                     |-----ClassCastException
 *                     |-----NumberFormatException
 *                     |-----InputMismatchException
 *                     |-----ArithmeticException

 

 

II. Common exceptions

1. Abnormal operation

ArrayIndexOutOfBoundsException:
public class test {
    public static void main(String[] args) {
        String[] arr = new String[]{"str1", "str2", "str3"};
        System.out.println(arr[3]);
    }
}
NullPointerException:
public class test {
    public static void main(String[] args) {
        Person p = new Person();
        p = null;
        System.out.println(p.name);//NullPointerException
    }
}

class Person{
    String name;
    int age;
}
ArithmeticException:
public class test {
    public static void main(String[] args) {
        int a = 10;
        int b = 0;
        System.out.println(a / b);//ArithmeticException: / by zero
    }
}
ClassCastException:
public class test {
    public static void main(String[] args) {
        Object obj = new Date();
        test t = (test)obj;
        System.out.println(t);//ClassCastException
    }
}

NumberFormatException:

public class test {
    public static void main(String[] args) {
        String s = "abc";
        int i = Integer.parseInt(s);
        System.out.println(i);//NumberFormatException
    }
}

InputMismatchException:

public class test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int score = scan.nextInt();
        //If the input in the console is not int Type, exception will be reported
        System.out.println(score);
        scan.close();
    }
}

2. Compile time exception

    @Test
    public void test7(){
//        File file = new File("hello.txt");
//        FileInputStream fis = new FileInputStream(file);
//        
//        int data = fis.read();
//        while(data != -1){
//            System.out.print((char)data);
//            data = fis.read();
//        }
//        
//        fis.close();
        
    }

3, Exception handling

1. Grabbing and throwing model

Process 1: "throwing"

During the normal execution of the program, once an exception occurs, an object corresponding to the exception class will be generated at the exception code and thrown. Once the object is thrown, the subsequent code is no longer executed.

Generation of exception object:

Exception objects automatically generated by the system

Generate an exception object manually and throw (throw)

Process 2: "grasp"

It can be understood as an exception handling method: ① try catch finally ② throws

2. Two methods of exception handling

2.1 mode 1: try catch finally

Format:

try{

Code with possible exception;

}Catch (exception type 1 variable 1){

The first is the way of exception handling;

}

Catch (exception type 2 variable 2){

The second is the method of exception handling;

}

Catch (exception type 3 variable 3){

The third way of exception handling;

}

...

finally{

Code that must be executed;

}

public class test {
    public static void main(String[] args) {
        String[] arr = new String[]{"str1", "str2", "str3"};
        try {
            for (int i = 0; i <= arr.length; i++) {
                System.out.println(arr[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Processing completed");
        }
    }
}

Explain:

① finally is optional, and the code must be executed;

② If the exception type in catch satisfies the child parent relationship, the child must be declared on the parent class. Otherwise, report the error;

③ Variables declared in the try structure cannot be called after the try structure is released

④ Try catch finally structure can be nested

⑤ Common methods of exception object processing: ① String getMessage() ② printStackTrace()

2.2 mode 2: throws + exception type

 

 

public class test {
    public static void main(String[] args) {
        test t = new test();
        try {
            t.readFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void readFile() throws IOException {
        FileInputStream in = new FileInputStream("atguigushk.txt");
        int b; b = in.read();
        while (b != -1) {
            System.out.print((char) b);
            b = in.read();
        }
        in.close();
    }
}

4, Throw an exception manually

Interview question: the difference between throw and throws?

throw: refers to the process of throwing an exception class object and generating an exception object. Declared in the method body.

throws: a method of exception handling, declared at the declaration of a method.

class Student{
    private int id;

    public void regist(int id) throws Exception {
        if (id > 0){
            this.id = id;
        }else{
            throw new Exception("The data you entered is illegal");
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}

5, Custom exception class

How to customize exception classes?

1. Inherit from the existing Exception classes: RuntimeException, Exception

2. Provide global constant: serialVersionUID

3. Provide heavy-duty constructors;

class Student{
    private int id;

    public void regist(int id) throws Exception {
        if (id > 0){
            this.id = id;
        }else{
            throw new MyException("The data you entered is illegal");
        }
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                '}';
    }
}

class MyException extends Exception{
    static final long serialVersionUID = -338751693453229948L;
    public MyException(){

    }

    public MyException(String msg){
        super(msg);
    }
}

 

 

Author: the beauty of Java

Date: March 30, 2020

Posted by jeethau on Mon, 30 Mar 2020 01:43:32 -0700