Definition of exceptions

In the Java language, anomalies that occur during program execution are called “exceptions.” (Syntax errors and logic errors during development are not exceptions)

1. Architecture of exceptions

Exception events that occur during the execution of a Java program can be classified into two categories:

  • Error: A serious problem that the Java VIRTUAL machine cannot resolve. Such as: JVM system internal errors, resource exhaustion and other serious situations. Such as:StackOverflowErrorAnd OOM. You don’t usually write specific code to handle it.
  • Exception: Other general problems caused by programming errors or accidental external factors can be handled using targeted code. Such as:
    • Null pointer access
    • Attempted to read a file that did not exist
    • Network connection down
    • Array script is out of bounds
Abnormal architecture * Java. Lang. Throwable * | -- -- -- -- - Java. Lang. Error: don't usually write specific code for processing. * | -- -- -- -- - Java. Lang. Exception: for Exception handling * | -- -- -- -- -- - compile time anomaly (checked) won't generate bytecode file * | -- -- -- -- -- IOException * | -- -- -- -- -- FileNotFoundException * | -- - | ClassNotFoundException * -- -- -- -- -- - a runtime exception (unchecked, RuntimeException) * | -- -- -- -- -- NullPointerException// The null pointer is abnormal
 * 					|-----ArrayIndexOutOfBoundsException// Array corner is out of bounds
 * 					|-----ClassCastException// Type conversion exception
 * 					|-----NumberFormatException// The encoding format is abnormal
 * 					|-----InputMismatchException// Input does not match
 * 					|-----ArithmeticException// Arithmetic exception

Copy the code

Inheritance of exception classes in Java

2. Exceptions can be classified into two categories according to the time of occurrence

  • Compile-time exception: Exceptions that may occur when the javac.exe command is executed:

    An exception that the compiler requires to be handled. That is, the program is running due to external factors caused by the general anomaly. The compiler requires Java programs to catch or declare all compile-time exceptions, which can have unexpected results if the program does not handle them.

  • Runtime exception: Exception that occurs when the java.exe command is executed:

    An exception that is not mandated by the compiler. Generally refers to the programming logic error, is the programmer should actively avoid its occurrence exception. The java.lang. Runtime Exception class and its subclasses are Runtime exceptions. This type of exception may not be handled because it is very common and may affect the readability and efficiency of the program.

3. Common exception types

/ / * * * * * * * * * * * * * * * * * * the following is a runtime exception * * * * * * * * * * * * * * * * * * * * * * * * * * *
//ArithmeticException
@Test
public void test6(a){
    int a = 10;
    int b = 0;
    System.out.println(a / b);
}

//InputMismatchException
@Test
public void test5(a){
    Scanner scanner = new Scanner(System.in);
    int score = scanner.nextInt();
    System.out.println(score);

    scanner.close();
}

//NumberFormatException
@Test
public void test4(a){

    String str = "123";
    str = "abc";
    int num = Integer.parseInt(str);	
}

//ClassCastException
@Test
public void test3(a){
    Object obj = new Date();
    String str = (String)obj;
}

//IndexOutOfBoundsException
@Test
public void test2(a){
    //ArrayIndexOutOfBoundsException
    // int[] arr = new int[10];
    // System.out.println(arr[10]);
    //StringIndexOutOfBoundsException
    String str = "abc";
    System.out.println(str.charAt(3));
}

//NullPointerException
@Test
public void test1(a){		
    // int[] arr = null;
    // System.out.println(arr[3]);

    String str = "abc";
    str = null;
    System.out.println(str.charAt(0));

}

/ / * * * * * * * * * * * * * * * * * * the following is a compile time exception * * * * * * * * * * * * * * * * * * * * * * * * * * *
@Test
public void test7(a){
    // 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();

}

Copy the code

Exception handling

1. Catch model of Java exception handling

** Process 1: “throw “** program in the normal execution of the process, once an exception occurs, it will generate a corresponding exception class object in the exception code. And throws this object. Once an object has been thrown, subsequent code is no longer executed.

About the generation of exception objects:

  • An exception object automatically generated by the system

  • Manually generate an exception object and throw it

Procedure 2: “catch “** can be interpreted as an exception handling method: (try-catch-finally) throws

2. Exception handling method 1: try-catch-finally

2.1 Instructions:

try{
    // Possible exception code

}catch(Exception type1The variable name1) {// Handle exception 1
}catch(Exception type2The variable name2) {// Handle exception 2
}catch(Exception type3The variable name3) {// Handle exception 3}...finally{
        // The code that must be executed
    }

Copy the code

Instructions:

  • finallyIt’s optional.
  • usetryThe possible exception code packaging, in the execution process, once the exception, will generate a corresponding exception class object, according to the type of this object, tocatchTo match
  • Once thetryMatches an exception object incatchWhen, entercatchTo handle exceptions. Once the processing is complete, jump out of the current onetry-catchStructure (not written herefinallyIn the case. Continue to execute the following code)
  • catchIf there is no parent-child relationship, it does not matter who is declared on top and who is declared on bottom.catchIf the exception type satisfies the parent-child relationship, the subclass must be declared above the parent class. Otherwise, an error will be reported
  • Common exception object processing methods: ①String getMessage()printStackTrace()
  • intryThe variables declared in the structure are again outtryStructure, cannot be called again
  • try-catch-finallyStructures can be nested

How do you look at compile-time and run-time exceptions in your code?

  • usetry-catch-finallyCompile-time exceptions are handled so that the program does not report an error at compile time, but can still report an error at run time. The equivalent of usingtry-catch-finallyDelay a compile-time exception until run time.
  • In development, we don’t usually write for runtime exceptions because they are commontry-catch-finally. But for compile-time exceptions, it’s important to consider exception handling.

2.2. finally

  • finallyIs optional
  • finallyDeclaration is the code that must be executed. Even if there’s another exception in the catch,tryContained in thereturnStatement, orcatchIn thereturnContains statements, etc.,finallyThe code in is also executed.
  • Resources such as database connections, input/output streams, and network programming sockets cannot be reclaimed automatically by the JVM. We need to release resources manually. At this point the resource release code needs to be declared infinallyIn the.

3. Exception Handling Method 2:

Throws + The exception type is written on the method declaration. Specifies the type of exception that may be thrown when this method executes. Once an exception occurs during the execution of the method body, an exception class object will still be generated in the exception code. When this object meets the post-throws exception type, it will be thrown. Exception code subsequent code, no longer executed!

4. Compare the two treatments

Try-catch-finally actually handles an exception. Throws the exception to the caller of the method. It doesn’t really handle the exception.

5. How do you choose between two approaches in development?

  • If the overridden method in the parent class does notthrowsThe subclass override method cannot be used eitherthrowsMeans that if a subclass overrides an exception in a method, it must usetry-catch-finallyIs processed.
  • In method A, several other methods are called successively, and these methods are executed in a progressive relationship. We recommend using these methodsthrowsIs processed in a way. Execution method A can be consideredtry-catch-finallyIs processed.

Add: One of the rules of method rewriting is that a method overridden by a subclass can throw no more than the type of exception thrown by a method overridden by its parent class

Manually throw exception objects

1. Instructions

During program execution, in addition to automatically throwing an exception object, we can also manually throw an exception object.

2. Classic interview questions

Throws throws an exception class object, the exception object generation process. The declaration is in the method body. Throws is a method of exception handling declared at the method declaration.

3. Code examples

class Student{

    private int id;

    public void regist(int id) throws Exception {
        if(id > 0) {this.id = id;
        }else{
            // Manually throw an exception object
            // throw new RuntimeException(" The data you entered is invalid!" );
            // throw new Exception(" The data you entered is invalid!" );
            throw new MyException("You cannot enter negative numbers."); }}@Override
    public String toString(a) {
        return "Student [id=" + id + "]"; }}Copy the code

Custom exception classes

1. How to customize exception classes

  • Inherited from the present exception structure:RuntimeException 、Exception
  • Provide global constants:serialVersionUID(Unique identification of a class)
  • Provides an overloaded constructor

2. Code examples

public class MyException extends Exception{

    static final long serialVersionUID = -7034897193246939L;

    public MyException(a){}public MyException(String msg){
        super(msg); }}Copy the code