Summary of abnormal knowledge points

abnormal

First, attach a mind map:

Concept of exception

Various problems in the procedure In life, the doctor said that there is a problem in a part of your body, which is different from the normal situation and will be affected. In the procedure, it means:

Exception: refers to an abnormal condition during the operation of the program, which will eventually lead to the abnormal stop of the JVM.
In object-oriented programming languages such as Java, the exception itself is a class. Generating an exception is to create an exception object and throw an exception object. The way Java handles exceptions is interrupt handling.
Note: exceptions do not refer to syntax errors. If the syntax is wrong and the compilation cannot pass, bytecode files will not be generated and will not run at all.

Abnormal system

The exception mechanism actually helps us find problems in the program. The root class of the exception is Java Lang. throwable has two subclasses: Java Lang. error and Java Lang. exception, commonly referred to as exception, refers to Java lang.Exception

Throwable system:

  • Error: a serious error. An error that cannot be handled through exception handling is like a terminal disease, which can only be prevented in advance.
  • Exception: exception. After the exception occurs, the programmer can correct it through code, so that the program can continue, such as cold and appendicitis.

Process analysis of exception generation:

public static void main(String[] args) {
		// Create an array of type int
		int[] arr = {1,2,3};
		int e = getElement(arr, 3);
		System.out.println(e);	
	}
	/*
	 *   Parameters:
	 * 		int[]  arr
	 *       int   index
	 */
	public static int getElement(int[] arr,int index) {
		int e = arr[index];
		return e;
	}

Exception handling

Five keywords of Java exception handling: try catch finally throw throws
Throw exception
When compiling a program, we must consider the possible problems of the program For example: when defining a method, the method needs to accept parameters. For users, when calling a method, they need to accept parameters. First, they need to judge the legitimacy of the parameter data. If the data is illegal, they should tell the caller to pass in the legitimate data At this time, you need to throw an exception to tell the caller
In java, a keyword throw is provided, which is used to throw a specified exception object

  1. Create an exception object and encapsulate some prompt information (the information can be written by yourself)
  2. You need to inform the caller of this exception object, which can be completed through the keyword throw Throw throws an exception object. Throw is generally used in a method to throw a specific exception object, throw the exception object to the caller, and end the execution of the method

Use format:

throw new Exception class name(parameter)

Example:

// Throw a null pointer exception to the caller
throw new NullPointerException("To access arr Array does not exist, value is null");
// Throw an index out of bounds exception to the caller
throw new IndexOutOfBoundsException("The index is out of range for reference");

Objects non null judgment

In this class, some static and practical methods are provided. If the method is nill safe (null pointer safe) or null tolerant (null pointer tolerant), the null value of the object is thrown an exception in its source code.

  • public static T requireNonNull(T obj): check that the specified reference object is not a null value
public static <T> T requirelNonNull(T obj) {
if (obj == null)
throw new Nul PointerExcept ion();
return obj;
}

Declare exception handling - throws

Declare exception: identify the problem and report it to the caller. If a compile time exception is thrown through throw in the method and not handled through capture (ry.catc), it must be declared through throws for the caller to handle.
The keyword throws is used in the declaration of a method to indicate that it does not handle exceptions and remind the caller. The call of the method carries exception information, and whoever calls it will handle it
Format of declaring exception handling:

Modifier return value type method name (parameter list) throws Exception class name 1,Exception class name 2,...{}

Example code:

public class ThrowsDemo01{
	public static void main(String[] args){
		read("C:/a.txt");
	}
	public static void read() throws FileNotFoundException{
		//Check if the path you pass is not in txt terminated
		if(!path.endWith(".txt")){
			//Throw a file not found exception
			throw new FileNotFoundException("File not found");
		}
	}
}

Catch exception try – catch

If an exception occurs, the program will be terminated immediately

  1. If the throw keyword is used for declarative processing, it is handled by the caller of the method (very dangerous)
  2. Use the statement block of try catch in the method to handle exceptions

try catch is to catch exceptions

  • Catch exception: in java, the exception is captured by targeted statements, and the exception can be handled in a specified way
    Format of exception capture:
try {
1// Write the possible exception code
} catch (Exception type e) {
//Logic code for handling exceptions
1/Log//Print abnormal information 1 / continue to throw up
}

try: the code in which exceptions may occur in this statement block

Catch: it is used to catch certain exceptions and handle the caught exceptions.

Note: try and catch cannot be used alone. It is generally recommended to use them together.

Code demonstration:

public class TryCatchDemo {
    public static void main(String[] args) {
        try {
             readFile("D:\\a.txt");
        } catch (FileNotFoundException e) {//What exception types need to be defined in parentheses?
            // The type thrown in try is defined as the exception type in parentheses
            // Print exception information
            System.out.println(e);
        }
       System.out.println("The program is loaded down...");
    }
    
    public static void readFile(String path) throws FileNotFoundException {
        if (!path.startsWith("C:")) {
            throw new FileNotFoundException("The file passed is not in C Disk, file not found exception");
        }
    } 
}
How to get exception information

Throwable class defines - some common apl methods

  • public String getMessage(): get the description and reason of the exception (prompt the user to see, prompt the error reason)
  • public String toString): get the type and description of the exception
  • public void printStackTrace(): print abnormal trace stack information and output it to the console
    It includes the type of exception, the reason for the exception, and the location of the exception. The printStackTrace() method is generally used in the development and debugging stages

finally statement block

Finally: there are some specific code blocks that need to be executed no matter whether an exception occurs or not When an exception occurs in the program, it will cause the jumping of the program, resulting in some code that can not be loaded. The finally statement block is used to solve this problem. The code stored in the finally statement block is generally bound to be executed

What kind of code must be executed in the end?

For example, when some physical resources (disk files / network connections / data connections) are opened in try, we generally have to close them after use. We can use the finally statement block to achieve this

Syntax format of finally statement block:

try{
	//
}catch(Exception type e){
	//...
}
......
finally{
	//...
}

Note: the catch statement block in the middle can be omitted. finally, it cannot be used alone. It is recommended to use it together

Code demonstration:

public class FinallyDemo06{
	public static void main(String[] args){
		try{
			System.out.println("open IO flow");
			readFile("b.txt");
		}catch(IOException e){
			e.printStackTrace();
		}finally{
			System.out.println("No matter how the program runs,It must be executed here");
			System.out.println("close IO flow");
		}
	
	}
	public static void readFile(String path) throws IOException{
		if(!path.endsWith(".txt")){
			throw new IOException("The suffix of the file is incorrect...");
		}
		System.out.println("The suffix of the file is correct,Read the file!");
	}
}

Remarks: 1 If the finally statement block has a return statement
2. when only the relevant methods for exiting the JVM are called in try or catch, finally will not be executed. Otherwise, finally will be executed forever

Abnormal precautions

When there are multiple exceptions in the programmer, how to catch and deal with them?
1. Handle multiple exceptions separately
2. Multiple exceptions are captured at one time and processed multiple times
3. Multiple exceptions are captured and handled at one time
Generally, we use the method of one capture and multiple processing. The format is as follows:

try {
//Code with possible exceptions multiple exceptions
} catch (Exception type A e) { //When an A exception occurs in the try, the catch is used to catch it
//Logic for handling exceptions
} catch (Exception type B e) {//This catch is used to catch the B exception in the try
//Logic for handling exceptions
}
.....
.....

Note: this exception handling method requires that the exceptions of multiple catches cannot be the same, and if there is a child parent relationship between multiple exceptions in a catch, the handling of child exceptions is above the handling of parent exceptions, and the handling of parent exceptions is below

  • When a runtime exception is thrown, it can not be handled, that is, it is not caught or declared to be thrown
  • If there is a return statement in finally, the result value in the finally statement block will always be returned
  • If the parent class throws multiple exceptions, when overriding the parent method, the child class throws the same exception as the parent class, or the child of the parent class exception, or does not throw an exception
  • If the parent method does not throw an exception, it is impossible for the subclass to throw an exception when overriding the method. At this time, an exception is generated in the subclass method, which can only be caught and handled, and cannot be declared to be thrown

Custom exception

summary

Java provides different exception classes according to different situations. The exception classes officially provided by JDK are always limited. In most cases, we need to customize the exception classes according to our business needs For example: abnormal negative age Negative score exception, login exception, registration exception, etc

What is a custom exception class?
An exception class defined according to the exception of its own business in development
eg. I want to customize a business logic exception class: Registration exception RegisterException
How are exception classes defined?

  1. Customize a compile time exception, and the custom class inherits from Java lang.Exception
  2. Customize a runtime exception class, which inherits from Java lang.RuntimeException

Custom exception exercise:
Simulate the registration operation. If the user exists, throw an exception and prompt: pro, your name has been registered. Change your name!

// First, define a registered exception class registerexception -- > business logic exception class
public class RegisterException extends RuntimeException {
    
    // Empty parameter structure
    public RegisterException(){}
    
    // Parametric structure
    public RegisterException(String message) {
        super(message);
    }
}

public class Demo {
    // Multiple account names already exist in the simulation database using array
    public static String[] names = {"Xiao Sun","Xiao Wang","Xiao Zhao"};
    
    public static void main(String[] args) {
        // Scanner
        Scanner scan = new Scanner(System.in);
        String name = scan.next();   
        // Verify whether the account has been registered
       try {
           // Code that may throw exceptions
           checkName(name);// If no exception occurs, the registration is successful
           System.out.println("Registration succeeded!")
           names = Arrays.copyOf(names,names.length+1);
           names[names.length-1] = name;
       } catch (RegisterException e) {
          // Exception handling logic
           e.printStackTrace();
       }           
    }
     
    // Verify whether the account has been registered
    public static boolean checkName(String usernmae) throws RegisterException {
        for (String name : names) {
            if (name.equals(username)) {
                // If it indicates that the name has been registered, a registration exception will be thrown
                throw new RegisterException("dear,Your name has been registered. Please change your name!");
            }
        }
        return true;
    }
}

Tags: Java

Posted by jasoncable on Tue, 03 May 2022 11:10:50 +0300