java study notes-exceptions and threads

Exceptions and Threads
1. Exceptions
Description: The information comes from the video of dark horse programmers, personal excerpts into notes.
1.1 Concept The
abnormal situation that occurs during the execution of the program will eventually cause the JVM to stop abnormally.
The exception is not a syntax error.
Exceptions actually help us find problems in the program
1.2 Exception system
Root category:java.lang.Throwable
Subcategory:java.lang.Errorandjava.lang.Exception(the exception we usually call)

Throwable system:
Error: serious error Error, can not be handled, can only be avoided in advance
Exception: indicates an exception, the programmer can correct it through code

Throwable common methods:
public void printStackTrace(): print the detailed information of the exception
public String getMessage(): get the reason for
Insert picture description here
the exception The most common exception: the array out of bounds exception

2. Exception handling

First know that five keywords are used to handle exceptions: try, catch, final, throw, throws

2.1 Throw an exception

When writing a program, we must consider the situation where the program has problems.
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 make a legal judgment on the parameter data. If the data is not legal, you should tell the caller to pass the legal data. Come in. At this time, you need to use the method of throwing an exception to tell the caller.
How to do it?
In java, a throw keyword is provided, which is used to throw a specified exception.
1. Create an exception object. Encapsulate some prompt information (information is self-made)
2. Need to inform the caller of this exception object, and use throw to inform.
Usage format:
throw new exception class name (parameter)
example:
throw new NullPointerException ("the array to be accessed does not exist");

2.2 Objects non-empty judgment

Objects class: consists of some static practical methods, these methods are null-save (null pointer safe) or
null-tolerant (tolerant of null pointers), in its source code, the value of the object null is thrown exception operation

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

2.3 Declare anomalies throws
Declare anomalies: identify the problem and report it to the caller. If a compile-time exception is thrown in the method through throw without catching it, then it must be declared through throws for the caller to handle it.

Summary: The keyword throws is used on method declarations to indicate that the current method does not handle exceptions, but to remind the caller of the method to handle exceptions.

Declare exception format:
modifier return value type method name (parameter) throws exception class name 1, exception class name 2...{}

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 handle the exception.

The try-catch method is to catch exceptions.
Catch exceptions: In java, exceptions are captured by targeted statements, and exceptions can be handled in a specified manner.
grammar:

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

How to get the exception information::
public String getMessage()Get the description and reason of the exception (when prompted to the user, it will prompt the cause of the error.

public void printStackTrace() : Print the abnormal trace stack information and output to the console.

2.4 finally code block
The code here needs to be executed regardless of whether an exception occurs.
What code must be executed?
When we open some physical resources (disk files/network connections/database connections, etc.) in the try block, we have to finally close the opened resources after using them.

2.5 Exception precautions
How to deal with multiple exception usage captures?
1. Multiple exceptions are handled separately
2. Multiple exceptions are captured at one time, and multiple exceptions are processed
3. Multiple exceptions are captured at one time

Generally use one capture and multiple processing

try{ write code that may cause exceptions } catch (exception type A e) {when type A appears in try, use this catch to catch exception handling code }



· Runtime exceptions can be thrown without handling. Neither capture nor declare to throw.
·If there is a return statement in final, always return the result in finally to avoid this situation.
·If the parent class throws multiple exceptions, when the subclass overrides the parent class method, it throws the same exception as the parent class or the parent class exception The subclass of or does not throw an exception
. The method of the parent class does not throw an exception, and the subclass cannot throw an exception when it overrides the method of the parent class. At this time, the subclass generates the exception, which can only be captured and processed, and cannot be declared to be thrown

Third, custom exceptions
There will be many exceptions in actual development, these exceptions are probably useless in the JDK definition.
First, we must 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 a method for judging 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; } }

4. Multithreading
4.1 Concurrency and Parallel
Concurrency: Two or more events occur in the same time period
Parallel: Two or more events occur at the same time

4.2 Processes and threads

Process: Refers to an application program running in memory. Each process has an independent memory space. An application program can run multiple processes at the same time; a process is also a one-time execution process of a program and is the basic unit of a system running program; system Running a program is the process of a process from creation, operation to death.
Thread: A thread is an execution unit in a process, responsible for the execution of the program in the current process, and 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.

Thread scheduling
1. Time-sharing scheduling
All threads use the right to use the CPU in turn, and evenly allocate the time each thread occupies the CPU.
2. Preemptive scheduling
gives priority to threads with high priority to use the CPU. If the threads have the same priority, they will Choose one randomly (thread randomness), and Java uses preemptive scheduling.

Guess you like

Origin blog.csdn.net/weixin_45663946/article/details/108423894