day05 [exception, thread]

day05 [exception, thread]

primary coverage

  • Exception, thread

Teaching objectives

  • Be able to distinguish between exceptions and errors in programs
  • Say the classification of exceptions
  • Say how the virtual machine handles exceptions
  • Three common run-time exceptions are listed
  • Be able to handle exceptions using the try... catch keyword
  • Be able to handle exceptions using the throws keyword
  • Ability to customize exception classes
  • Able to handle custom exception classes
  • Say the concept of process
  • Say the concept of thread
  • Be able to understand the difference between concurrency and parallelism
  • Ability to start new threads

Chapter I exceptions

1.1 abnormal concept

Abnormal means abnormal. In life: the doctor said that there is an abnormality in a part of your body, which is a little different from normal, and the function of this part will be affected In the program, it means:

  • Exception: refers to an abnormal situation during the execution 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.

Exceptions do not refer to syntax errors. If the syntax is wrong, the compilation fails, no bytecode file will be generated, and it cannot run at all

1.2 abnormal system

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

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-8ohTu1Zs-1641983130268)(img \ exception system. png)]

Throwable system:

  • Error: a serious error. An error that cannot be handled can only be avoided in advance, like a terminal disease.
  • Exception: indicates an exception. After an exception is generated, the programmer can correct it through code to make the program continue to run. It must be handled. Like cold, appendicitis.

Common methods in Throwable:

  • public void printStackTrace(): print the details of the exception.

    It includes the type of exception, the reason for the exception, and the location of the exception. printStackTrace must be used in the development and debugging stages.

  • public String getMessage(): get the reason for the exception.

    When prompted to the user, the error reason will be prompted.

  • public String toString(): get the exception type and exception description information (not required).

When an exception occurs, don't be nervous. Copy the simple class name of the exception to the API for query.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-TCIytnLM-1641983130271)(img \ simple exception view. bmp)]

1.3 anomaly classification

We usually refer to exceptions, because once such exceptions occur, we need to correct the code and repair the program.

Classification of exceptions: check exceptions at compile time or run time?

  • Compile time exception: checked exception. At compile time, it is checked. If the exception is not handled, the compilation fails. (such as abnormal date formatting)
  • Runtime exception: runtime exception. During runtime, check for exceptions At compile time, run exceptions are not detected by the compiler (no errors are reported). (e.g. mathematical abnormality)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RWnw0A3p-1641983130274)(img \ abnormal classification. png)]

1.4 analysis of abnormal generation process

First run the following program, which will generate an array index out of bounds exception ArrayIndexOfBoundsException. We use diagrams to analyze the process of exception generation.

Tool class

public class ArrayTools {
    // Gets the elements of a given array through the given subscript.
    public static int getElement(int[] arr, int index) {
        int element = arr[index];
        return element;
    }
}

Test class

public class ExceptionDemo {
    public static void main(String[] args) {
        int[] arr = { 34, 12, 67 };
        intnum = ArrayTools.getElement(arr, 4)
        System.out.println("num=" + num);
        System.out.println("over");
    }
}

Diagram of the execution process of the above procedures:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-69juGOGu-1641983130278)(img \ exception generation process. png)]

Chapter II exception handling

Five keywords for Java exception handling: try, catch, finally, throw, throws

2.1 throw exception

When writing a program, we must consider the problem of the program. For example, when defining a method, the method needs to accept parameters. Then, when calling the method to use the received parameters, you first need to judge the validity of the parameter data. If the data is illegal, you should tell the caller to pass in the legal data. In this case, you need to tell the caller by throwing an exception.

In java, a throw keyword is provided, which is used to throw a specified exception object. So, how to throw an exception?

  1. Create an exception object. Encapsulate some prompt information (the information can be written by yourself).

  2. This exception object needs to be notified to the caller. How to tell? How do I pass this exception object to the caller? This can be done by using the keyword throw. Throw exception object.

    Throw is used in a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.

Use format:

throw new Exception class name(parameter);

For example:

throw new NullPointerException("To access arr Array does not exist");

throw new ArrayIndexOutOfBoundsException("The index does not exist in the array and is out of range");

After learning the format of throwing exceptions, we demonstrate the use of throw through the following program.

public class ThrowDemo {
    public static void main(String[] args) {
        //Create an array 
        int[] arr = {2,4,52,2};
        //Find the corresponding element according to the index 
        int index = 4;
        int element = getElement(arr, index);

        System.out.println(element);
        System.out.println("over");
    }
    /*
     * Find the corresponding element in the array according to the index
     */
    public static int getElement(int[] arr,int index){ 
       	//Judge whether the index is out of bounds
        if(index<0 || index>arr.length-1){
             /*
             If the judgment conditions are met, the method cannot continue operation after throw ing the exception object.
             This will end the execution of the current method and notify the caller of the exception. At this time, it needs to be solved through exceptions. 
              */
             throw new ArrayIndexOutOfBoundsException("Man, the corner marker is out of bounds~~~");
        }
        int element = arr[index];
        return element;
    }
}

Note: if a problem occurs, we will throw the problem description class, that is, the exception, that is, return the problem to the caller of the method.

So what should the caller do? One is to capture, and the other is to continue to declare the problem and use the throws declaration.

2.2 non empty objects judgment

Remember when we learned about an object class? It was mentioned that it consists of some static and practical methods. These methods are null save (null pointer safe) or null tolerance (null pointer tolerant). In its source code, we threw an exception to the null value of the object.

  • Public static < T > t requirenonnull (t obj): check that the specified reference object is not null.

Looking at the source code, it is found that an exception is thrown for null:

public static <T> T requireNonNull(T obj) {
    if (obj == null)
      	throw new NullPointerException();
    return obj;
}

2.3 declare exception throws

Declare exception: identify the problem and report it to the caller. If a compile time exception is thrown through throw in the method without capture and processing (this method will be explained later), it must be declared through throws for the caller to handle.

The keyword throws is used on the method declaration to indicate that the current method does not handle exceptions, but reminds the caller of the method to handle exceptions (throw exceptions)

Declaration exception format:

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

Code demonstration for declaring exceptions:

public class ThrowsDemo {
    public static void main(String[] args) throws FileNotFoundException {
        read("a.txt");
    }

    // If a problem occurs when defining a function, it needs to be reported to the caller. This can be declared by using the throws keyword on the method
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//If it's not a.txt 
            // I assume that if a.txt does not think the file does not exist, it is an error, that is, an exception throw
            throw new FileNotFoundException("file does not exist");
        }
    }
}

Throws is used to declare exception classes. If multiple exceptions may occur in this method, multiple exception classes can be written after throws, separated by commas.

public class ThrowsDemo2 {
    public static void main(String[] args) throws IOException {
        read("a.txt");
    }

    public static void read(String path)throws FileNotFoundException, IOException {
        if (!path.equals("a.txt")) {//If it's not a.txt 
            // I assume that if a.txt does not think the file does not exist, it is an error, that is, an exception throw
            throw new FileNotFoundException("file does not exist");
        }
        if (!path.equals("b.txt")) {
            throw new IOException();
        }
    }
}

2.4 catch exception try... Catch

If an exception occurs, the program will be terminated immediately, so we have to deal with the exception:

  1. The method does not handle, but declares throws, which are handled by the caller of the method.
  2. Use the try catch statement block in the method to handle exceptions.

The way to try catch is to catch exceptions.

  • Catch exception: in Java, targeted statements for exceptions are caught, and exceptions can be handled in a specified way.

The syntax for catching exceptions is as follows:

try{
     Write code that may cause exceptions
}catch(Exception type  e){
     Code to handle exceptions
     //Log / print exception information / continue to throw exception
}

**try: * * write code that may cause exceptions in this code block.

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

Note: try and catch cannot be used alone, but must be used together.

The demonstration is as follows:

public class TryCatchDemo {
    public static void main(String[] args) {
        try {// When an exception occurs, there must be a handling method. Either capture or declare.
            read("b.txt");
        } catch (FileNotFoundException e) {// What needs to be defined in parentheses?
          	//What exception is thrown in try, and what exception type is defined in parentheses
            System.out.println(e);
        }
        System.out.println("over");
    }
    /*
     *
     * There are compile time exceptions in our current method
     */
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//If it's not a.txt 
            // I assume that if a.txt does not think the file does not exist, it is an error, that is, an exception throw
            throw new FileNotFoundException("file does not exist");
        }
    }
}

How to get exception information:

Some viewing methods are defined in the Throwable class:

  • public String getMessage(): get the description of the exception. When the user is prompted, the error reason will be prompted.

  • public String toString(): get the exception type and exception description information (not required).

  • public void printStackTrace(): print the abnormal tracking 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. printStackTrace must be used in the development and debugging stages.

2.4 finally code block

Finally: there are some specific codes that need to be executed whether an exception occurs or not. In addition, because the exception will cause program jump, some statements cannot be executed. Finally solves this problem. The code stored in the finally code block will be executed.

When must the code be finally executed?

When we open some physical resources (disk file / network connection / database connection, etc.) in the try statement block, we have to finally close the open resources after using them.

finally syntax:

try... catch... Finally: you need to handle exceptions and finally close resources.

Note: finally cannot be used alone.

For example, in the IO stream we learned later, when a resource of an associated file is opened, the program needs to close the resource regardless of the result.

finally, the code reference is as follows:

public class TryCatchDemo4 {
    public static void main(String[] args) {
        try {
            read("a.txt");
        } catch (FileNotFoundException e) {
            //What is captured is the compile time exception, and what is thrown is the run time exception 
            throw new RuntimeException(e);
        } finally {
            System.out.println("No matter what the program is, it will be executed here.");
        }
        System.out.println("over");
    }
    /*
     *
     * There are compile time exceptions in our current method
     */
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//If it's not a.txt 
            // I assume that if a.txt does not think the file does not exist, it is an error, that is, an exception throw
            throw new FileNotFoundException("file does not exist");
        }
    }
}

When try or catch is called to exit the relevant methods of JVM, finally will not execute at this time, otherwise finally will always execute.

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-uiy71dhr-1641983130282) (try. BMP if img \ is dead)]

2.5 abnormal precautions

  • How to deal with multiple exceptions using capture?

    1. Multiple exceptions are handled separately.
    2. Multiple exceptions are captured once and processed multiple times.
    3. Multiple exceptions are captured and processed at a time.

    Generally, we use the method of one capture and multiple processing. The format is as follows:

    try{
         Write code that may cause exceptions
    }catch(Exception type A  e){  When try Appear in A Type exception,Just use it catch To capture.
         Code to handle exceptions
         //Log / print exception information / continue to throw exception
    }catch(Exception type B  e){  When try Appear in B Type exception,Just use it catch To capture.
         Code to handle exceptions
         //Log / print exception information / continue to throw exception
    }
    

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

  • The runtime exception is thrown and can not be handled. Neither capture nor declare throw.

  • If finally has a return statement, always return the result in finally to avoid this situation

  • If the parent class throws multiple exceptions, when overriding the parent class 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.

  • The parent class method does not throw an exception, and the child class cannot throw an exception when overriding the parent class method. At this time, the subclass generates the exception, which can only be caught and processed, and cannot be declared and thrown

Chapter 3 custom exceptions

3.1 general

Why do I need to customize the exception class

We talked about different exception classes in Java, which respectively represent a specific exception. In the development, there are always some exceptions that SUN has not defined. At this time, we define the exception class according to the exception of our own business. For example, negative age, negative test scores and so on.

In the above code, it is found that these exceptions are internally defined in JDK, but many exceptions will occur in actual development. These exceptions are likely not defined in JDK, such as negative age and negative test scores So can you define exceptions yourself?

What is a custom exception class:

In development, define exception classes according to their own business exceptions

Customize a business logic exception: RegisterException. A registered exception class.

How to define exception classes:

  1. Customize a compile time exception: customize the class and inherit from Java lang.Exception.
  2. Customize a runtime exception class: customize the class and inherit it from Java lang.RuntimeException.

3.2 practice of customizing exceptions

Requirements: we simulate the registration operation. If the user name already exists, we throw an exception and prompt: pro, the user name has been registered.

First, define a login exception class RegisterException:

// Business logic exception
public class RegisterException extends Exception {
    /**
     * Empty parameter structure
     */
    public RegisterException() {
    }

    /**
     *
     * @param message Indicates an exception prompt
     */
    public RegisterException(String message) {
        super(message);
    }
}

Simulate the login operation, use the array to simulate the data stored in the database, and provide the method to judge whether the current registered account exists.

public class Demo {
    // The account already exists in the simulation database
    private static String[] names = {"bill","hill","jill"};
   
    public static void main(String[] args) {     
        //Call method
        try{
              // Possible exception codes
            checkUsername("nill");
            System.out.println("login was successful");//If there is no exception, the registration is successful
        }catch(RegisterException e){
            //Handling exceptions
            e.printStackTrace();
        }
    }

    //Judge whether the current registered account exists
    //Because it is a compile time exception and wants the caller to handle it, declare the exception
    public static boolean checkUsername(String uname) throws LoginException{
        for (String name : names) {
            if(name.equals(uname)){//If the name is in it, a login exception will be thrown
                throw new RegisterException("dear"+name+"Already registered!");
            }
        }
        return true;
    }
}

Chapter 4 multithreading

Before, the programs we learned were executed from top to bottom without jump statements. Now we want to design a program to listen to music while playing games. How to design it?

To solve the above problems, we have to use multi - process or multi - thread

4.1 concurrency and parallelism

  • Concurrency: two or more events occur in the same time period.
  • Parallel: two or more events occur at the same time (at the same time).

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gJ0liEOZ-1641983130286)(img \ parallel and concurrent. bmp)]

In the operating system, multiple programs are installed. Concurrency refers to that multiple programs run at the same time in a period of time. In a single CPU system, only one program can be executed at each time, that is, these programs run alternately in time-sharing, which just gives people the feeling that they run at the same time, because the time-sharing alternate running time is very short.

In multiple CPU systems, these programs that can be executed concurrently can be allocated to multiple processors (CPUs) to realize multi task parallel execution, that is, each processor is used to process a program that can be executed concurrently, so that multiple programs can be executed at the same time. At present, the multi-core CPU in the computer market is multi-core processor. The more cores, the more parallel processing programs, can greatly improve the efficiency of computer operation.

Note: a computer with a single core processor certainly cannot process multiple tasks in parallel. It can only run multiple tasks concurrently on a single CPU. Similarly, threads are the same. From a macro perspective, threads run in parallel, but from a micro perspective, they run in serial, that is, one thread runs one thread. When the system has only one CPU, threads will execute multiple threads in a certain order. We call this situation thread scheduling.

4.2 threads and processes

  • Process: refers to an application running in memory. Each process has an independent memory space. An application can run multiple processes at the same time; Process is also an execution process of the program and the basic unit of the system running program; A system running a program is a process from creation, running to extinction.

  • Thread: a thread is an execution unit in a process. It is responsible for the execution of programs in the current process. There is at least one thread in a process. There can be multiple threads in a process, and this application can also be called a multithreaded program.

    In short: after a program runs, there is at least one process, and a process can contain multiple threads

We can right click the task bar at the bottom of the computer - > open the task manager to view the progress of the current task:

process

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-SyLzjfV6-1641983130289)(img \ process concept. png)]

thread

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-aj3gtDx1-1641983130294)(img \ thread concept. png)]

Thread scheduling:

  • Time sharing scheduling

    All threads use the right to use the CPU in turn, and allocate the CPU time of each thread equally.

  • preemptive scheduling

    Give priority to the threads with high priority to use CPU. If the threads have the same priority, one will be selected randomly (thread randomness). Java uses preemptive scheduling.

    • Set thread priority

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Of6LFeM3-1641983130301)(img / set thread priority. bmp)]

    • Detailed explanation of preemptive scheduling

    Most operating systems support concurrent running of multiple processes, and almost all current operating systems support running multiple programs at the same time. For example, now we use the editor and screen recording software in class. At the same time, we also open drawing board, dos window and other software. At this time, these programs are running at the same time, "it feels like these software are running at the same time".

    In fact, CPU (central processing unit) uses preemptive scheduling mode to switch between multiple threads at high speed. For a core of the CPU, only one thread can be executed at a certain time, and the switching speed of the CPU between multiple threads is faster than our feeling. It seems that it runs at the same time.
    In fact, multithreaded programs can not improve the running speed of programs, but can improve the running efficiency of programs and make the CPU utilization higher.

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-BjTJbAa4-1641983130304)(img / preemptive scheduling. bmp)]

4.3 creating thread classes

Java uses Java Lang. Thread class represents threads. All Thread objects must be instances of Thread class or its subclasses. The role of each Thread is to complete a certain task. In fact, it is to execute a program flow, that is, a piece of code executed in sequence. Java uses Thread executors to represent this program flow. The steps to create and start a multithread by inheriting the Thread class in Java are as follows:

  1. Define a subclass of the Thread class and override the run() method of the class. The method body of the run() method represents the tasks that the Thread needs to complete. Therefore, the run() method is called the Thread execution body.
  2. Create an instance of Thread subclass, that is, create a Thread object
  3. Call the start() method of the thread object to start the thread

The code is as follows:

Test class:

public class Demo01 {
	public static void main(String[] args) {
		//Create custom thread object
		MyThread mt = new MyThread("New thread!");
		//Open new thread
		mt.start();
		//Execute a for loop in the main method
		for (int i = 0; i < 10; i++) {
			System.out.println("main Thread!"+i);
		}
	}
}

Custom thread class:

public class MyThread extends Thread {
	//Defines the constructor for the specified thread name
	public MyThread(String name) {
		//Call the constructor of the String parameter of the parent class to specify the name of the thread
		super(name);
	}
	/**
	 * Rewrite the run method to complete the logic executed by the thread
	 */
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(getName()+": Executing!"+i);
		}
	}
}

Keywords: Java JavaEE

Added by mayanktalwar1988 on Fri, 14 Jan 2022 06:49:06 +0200