Exception, thread

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:

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.

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。

Throwable system:

Common methods in throwable:

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

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?

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 {
    // 对给定的数组通过给定的角标获取元素。
    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:

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?

Use format:

throw new 异常类名(参数);

For example:

throw new NullPointerException("要访问的arr数组不存在");

throw new Arrayindexoutofboundsexception("该索引在数组中不存在,已超出范围");

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) {
        //创建一个数组 
        int[] arr = {2,4,52,2};
        //根据索引找对应的元素 
        int index = 4;
        int element = getElement(arr,index);

        System.out.println(element);
        System.out.println("over");
    }
    /*
     * 根据 索引找到数组中对应的元素
     */
    public static int getElement(int[] arr,int index){ 
       	//判断  索引是否越界
        if(index<0 || index>arr.length-1){
             /*
             判断条件如果满足,当执行完throw抛出异常对象后,方法已经无法继续运算。
             这时就会结束当前方法的执行,并将异常告知给调用者。这时就需要通过异常来解决。 
              */
             throw new Arrayindexoutofboundsexception("哥们,角标越界了~~~");
        }
        int element = arr[index];
        return element;
    }
}

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.

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:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{   }	

Code demonstration for declaring exceptions:

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

    // 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws关键字进行声明
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//如果不是 a.txt这个文件 
            // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
            throw new FileNotFoundException("文件不存在");
        }
    }
}

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")) {//如果不是 a.txt这个文件 
            // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
            throw new FileNotFoundException("文件不存在");
        }
        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:

The way to try catch is to catch exceptions.

The syntax for catching exceptions is as follows:

try{
     编写可能会出现异常的代码
}catch(异常类型  e){
     处理异常的代码
     //记录日志/打印异常信息/继续抛出异常
}

Try: write code that may cause exceptions in this code block.

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

The demonstration is as follows:

public class TryCatchDemo {
    public static void main(String[] args) {
        try {// 当产生异常时,必须有处理方式。要么捕获,要么声明。
            read("b.txt");
        } catch (FileNotFoundException e) {// 括号中需要定义什么呢?
          	//try中抛出的是什么异常,在括号中就定义什么异常类型
            System.out.println(e);
        }
        System.out.println("over");
    }
    /*
     *
     * 我们 当前的这个方法中 有异常  有编译期异常
     */
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//如果不是 a.txt这个文件 
            // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
            throw new FileNotFoundException("文件不存在");
        }
    }
}

How to get exception information:

Some viewing methods are defined in the throwable class:

Printstacktrace must be used for all types that contain exceptions.

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: it needs to handle exceptions, and finally close the resources.

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) {
            //抓取到的是编译期异常  抛出去的是运行期 
            throw new RuntimeException(e);
        } finally {
            System.out.println("不管程序怎样,这里都将会被执行。");
        }
        System.out.println("over");
    }
    /*
     *
     * 我们 当前的这个方法中 有异常  有编译期异常
     */
    public static void read(String path) throws FileNotFoundException {
        if (!path.equals("a.txt")) {//如果不是 a.txt这个文件 
            // 我假设  如果不是 a.txt 认为 该文件不存在 是一个错误 也就是异常  throw
            throw new FileNotFoundException("文件不存在");
        }
    }
}

2.5 abnormal precautions

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:

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:

// 业务逻辑异常
public class RegisterException extends Exception {
    /**
     * 空参构造
     */
    public RegisterException() {
    }

    /**
     *
     * @param message 表示异常提示
     */
    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 {
    // 模拟数据库中已存在账号
    private static String[] names = {"bill","hill","jill"};
   
    public static void main(String[] args) {     
        //调用方法
        try{
              // 可能出现异常的代码
            checkUsername("nill");
            System.out.println("注册成功");//如果没有异常就是注册成功
        }catch(RegisterException e){
            //处理异常
            e.printStackTrace();
        }
    }

    //判断当前注册账号是否存在
    //因为是编译期异常,又想调用者去处理 所以声明该异常
    public static boolean checkUsername(String uname) throws LoginException{
        for (String name : names) {
            if(name.equals(uname)){//如果名字在这里面 就抛出登陆异常
                throw new RegisterException("亲"+name+"已经被注册了!");
            }
        }
        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

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 alternating running time is very short.

In multiple CPU systems, Then these programs that can be executed concurrently can be allocated to multiple processors (CPU) 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 programs processed in parallel, can greatly improve the efficiency of computer operation.

4.2 threads and processes

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

@H_ 23_ 502@

thread

Thread scheduling:

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:

The code is as follows:

Test class:

public class Demo01 {
	public static void main(String[] args) {
		//创建自定义线程对象
		MyThread mt = new MyThread("新的线程!");
		//开启新线程
		mt.start();
		//在主方法中执行for循环
		for (int i = 0; i < 10; i++) {
			System.out.println("main线程!"+i);
		}
	}
}

Custom thread class:

public class MyThread extends Thread {
	//定义指定线程名称的构造方法
	public MyThread(String name) {
		//调用父类的String参数的构造方法,指定线程的名称
		super(name);
	}
	/**
	 * 重写run方法,完成该线程执行的逻辑
	 */
	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(getName()+":正在执行!"+i);
		}
	}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>