Summary of Java knowledge points [7] Abnormal

table of Contents

1. What is an exception

Second, defensive programming (the reason for the introduction of exceptions)

1. What is defensive programming

2. Two specific code manifestations of defensive programming

Three, the specific grammar of the exception

1.try

2.catch

3.finally

4.throw

5.throws

Four, Java's exception system

1. What is the exception system of Java

2. Checked exceptions and unchecked exceptions

3. Custom exception


1. What is an exception

An exception is a kind of error that occurs during the running of the program . There are many types of exceptions, each representing different meanings. Once a certain exception occurs, it will clearly tell the programmer the reason for the exception, so it is a good way to help us solve the problem.

Second, defensive programming (the reason for the introduction of exceptions)

1. What is defensive programming

In the process of running the program, if a program has no errors now, it does not mean that there will be no errors in the future, and it does not mean that there will be no errors when running on someone else’s machine... So, in order to avoid these problems as much as possible, when writing the program, we will We must first consider in many ways what kind of problems will arise, that is, " unspoken before you lose ", and then come up with corresponding solutions to these problems. In this way, it is defensive programming.

2. Two specific code manifestations of defensive programming

Take the king as an example:

① LBYL (no exceptions): Look Before Your Leap: Do a sufficient check before the operation. After checking the previous step, perform the next operation. If the previous step fails, the execution will not continue.

boolean ret=login();
if(!ret){
    //处理登录失败
    return;
}
ret=startMatch();
if(!ret){
    //处理匹配失败
    return;
}
ret=enterRoom();
if(!ret){
    //处理进入房间失败
    return;
}
ret=chooseHero();
if(!ret){
    //处理选择英雄失败
    return;
}

EAFP (Usage Abnormality): It's Easier to Ask Forgiveness than Permission: Cut first and play later .

try{
    login();
    startMatch();
    enterRoom();
    chooseHero();
    ...    
}catch(XXX){
    //处理异常的代码
}

Analysis: If an error occurs at a certain step, an exception will be thrown. Once an exception is thrown, it will enter the code such as catch to execute the exception handling logic.

Of the above two methods, the second one can be found to be better. It separates the normal flow of the program from the error handling, making it clearer and easier to understand!

Three, the specific grammar of the exception

1.try

Place code that may throw an exception

2.catch

Place the code used to handle exceptions and use it with try. When an exception occurs in the try, it will enter the catch to execute

Example ①

int[] a=null;
System.out.println(a[0]);
System.out.println("hello");

operation result

Analysis: If there is an exception in the code and try catch is not used, the exception will be handled by the JVM itself , and the program will be terminated directly and will not go down.

Example ②

try{
    System.out.println("try中异常之前的代码");
    int[] a=null;
    System.out.println(a[0]);
    System.out.println("try中异常之后的代码");
}catch(NullPointerException e){
    System.out.println("catch中的代码");
}

System.out.println("hello");

operation result

Analysis: try catch in order of execution : try to press the sequential code execution, if an exception occurs -> execution proceeds to catch (try the remaining code is not executed) -> When the catch is also executed, will be executed In the subsequent code, the program did not terminate abnormally.

Example ③

The type of the exception in the catch needs to match the type of the exception thrown to be able to handle it correctly, otherwise the logic in the catch cannot be executed, then the JVM will handle it itself.

try{
    System.out.println("try中异常之前的代码");
    int[] a=null;
    System.out.println(a[100]);
    System.out.println("try中异常之后的代码");
}catch(NullPointerException e){
    System.out.println("catch中的代码");
}

System.out.println("hello");

operation result

Analysis: a[100] This is an array subscript out-of-bounds exception, not a null pointer exception, so there is no match, the catch will not be processed, it will be processed by the JVM, and the program will be terminated directly.

Example ④

Use catch to catch multiple exceptions ( | )

try{
    System.out.println("try中异常之前的代码");
    int[] a=null;
    System.out.println(a[100]);
    System.out.println("try中异常之后的代码");
}catch(NullPointerException | ArrayIndexOutOfBoundsException e){
    System.out.println("catch中的代码");
}

System.out.println("hello");

Analysis: Use | to parallel the types of multiple exceptions, which is equivalent to "logical OR". Throwing any of these exceptions will trigger catch.

Example ⑤

There is a more absolute way to catch multiple exceptions ( Exception )

try{
    System.out.println("try中异常之前的代码");
    int[] a=null;
    System.out.println(a[100]);
    System.out.println("try中异常之后的代码");
}catch(Exception e){
    System.out.println("catch中的代码");
}

System.out.println("hello");

Analysis: Exception is a very high-level parent class. Null pointer exceptions and array subscript out-of-bounds exceptions are all subclasses of Exception. When catch matching, the type is not necessarily required to be exactly the same. If an exception is thrown Subclasses of the exception of the catch parameters are also possible (essentially up-casting). It is generally not recommended to use Exception because it is too lethal, and all exceptions are forcibly handled with the same logic.

3.finally

The code placed in finally will be executed, generally used for finishing work after exception handling, such as closing files and so on.

Example ①

Use finally to put it behind the try catch, and the logic in the finally is guaranteed to be executed .

try{
    System.out.println("try中异常之前的代码");
    int[] a={1,2,3};
    System.out.println(a[100]);
    System.out.println("try中异常之后的代码");
}catch(NullPointerException e){
    System.out.println("catch中的代码");
}finally {
    System.out.println("hello");
}

Analysis: The logic in finally will be executed regardless of whether an exception is triggered in the previous code. a[100] is an out-of-bounds exception of the array subscript, but the type of the parameter in the catch is a null pointer exception, and the type does not match, then the JVM will handle it, and the code in finally is still executed. So the file closing operation can be placed in finally.

Note: It is not recommended to write a return statement in finally. If there is a return statement in try and a return statement in finally, then the return statement in finally will be executed instead of the original return statement in try.

Example ②

Using finally to recycle resources is indeed more reliable, but the code is more troublesome to write, you can also use the try with resource mechanism provided by Java1.7 to complete this operation. ( Use try to be responsible for recycling resources )

try(Scanner sc=new Scanner(System.in)){
    int num=sc.nextInt();
    System.out.println(num);
}catch (InputMismatchException e){
    System.out.println("输入类型不匹配异常");
}

Analysis: Create the Scanner object in the () of try to ensure that the close method of Scanner is automatically called after the try is executed.

4.throw

Actively throw an exception object

Example①

public class Test2 {
    public static int divide(int x,int y){
        if(y==0){
            throw new ArithmeticException("此处抛出了一个算数异常");
        }
        return x/y;
    }
    public static void main(String[] args) {
        try{
            int ret=divide(10,0);
        }catch(ArithmeticException e){
            e.printStackTrace();
        }
    }
}

The printStackTrace() method can get some specific information about the exception.

5.throws

The annotation method may throw some exceptions

public class Test2 {
    public static int divide(int x,int y) throws ArithmeticException{
        if(y==0){
            throw new ArithmeticException("此处抛出了一个算数异常");
        }
        return x/y;
    }
    public static void main(String[] args) {
        try{
            int ret=divide(10,0);
        }catch(ArithmeticException e){
            e.printStackTrace();
        }
    }
}

Analysis: throws mark the divide method, you can clearly know that the divide method may throw ArithmeticException, and remind the caller of the method to handle these exceptions carefully~

Four, Java's exception system

1. What is the exception system of Java

Used to describe the exception classes provided in the Java standard library, and divided into those types.

note:

  • The upward arrow on the figure is actually a relationship such as "inheritance" or "implementation".
  • Error is a system-level exception, used internally by the JVM, and ordinary programmers should not use the Error system.
  • Exception is an application-level exception, and ordinary programmers want to use this set of series.

2. Checked exceptions and unchecked exceptions

Java language specification is derived from the class Error or RuntimeException class of all exceptions called non-checked exception , all the other exceptions referred checked exception.

Unchecked exception:

  • Can not show processing
  • Error: Error must be a very serious situation. Generally, the JVM machine hangs. At this time, as an application-level programmer, there is no way but to let it fend for itself.
  • RuntimeException: Some of the most common exceptions, with little impact.

Exception under investigation:

  • If this exception is thrown in a method, then the exception must be explicitly handled
  • There are two schemes: ① directly try catch ② using throws statement may throw this exception.

3. Custom exception

Custom exceptions usually inherit from Exception (checked) or RuntimeException (not checked).

Example: Implement a simple console version user login program, the program starts to prompt the user to enter the user name and password, if the user name and password are wrong, use a custom exception method to deal with

Custom NameException:

public class NameException extends Exception{
    public NameException(String str){
        super(str);
    }
}

Custom PasswdException:

public class PasswdException extends Exception{
    public PasswdException(String str) {
        super(str);
    }
}

Test class

import java.util.Scanner;

public class Test {
    private static String userName="ttlxbb";
    private static String userPassword="5201314";
 //主类
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入姓名");
        String name=sc.next();
        System.out.println("请输入密码");
        String password=sc.next();
        try{
        login(name,password);
        }catch(NameException | PasswdException e){
            e.printStackTrace();
        }
    }
 //login类
    public static void login(String name,String password)throws NameException, PasswdException {
        if(!name.equals(userName)){
            throw new NameException("用户名输入错误");
        }
        if(!password.equals(userPassword)){
            throw new PasswdException("用户密码输入错误");
        }
        System.out.println("登录成功!");
    }
}

operation result

Analysis: behind the login method throws NameException and PasswdException, indicating that the login method may throw these two exceptions. Then the exception object will be thrown and handed over to the superior caller for processing.

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/113112840