Java recognizes exceptions (simulates the king's login exception)

1. Exception: Program error thrown at runtime

Runtime means that the program has been compiled to get the class file, and then an error occurs when the JVM executes it.

(javac source file -> *.java -> *.class compilation process)

1. Division by zero exception

2. Null pointer exception

3. Array subscript out of bounds

two,

Two ways to avoid exceptions:

LBYL: fully checked before operation

EAFP: Do it first, then fix it when you encounter errors

The basic syntax of the exception: (simulate the execution process of the king's login game)

//模拟王者登录游戏的执行过程
        try {
            //存放所有可能出现异常的代码
            login();
            loadGame();
            chooseHero();
            biubiubiu();
        }
        //catch 捕获相应的异常 {}内是出现相应异常的处理方式
        catch (登陆异常){}
        catch (载入游戏异常){}
        catch (选取英雄异常){}
        catch (正常游戏时出现的异常){}
        
        finally{
            //不是强制书写
            //无论是否发生异常,都会执行finally代码块,一般执行资源的释放
            //关闭资源的处理
        }

1. Use try..catch.. to handle exceptions

Put the code that may report an error into try and catch it with catch. When an exception occurs, it does not affect the normal code.

 2. Multiple catch blocks

Write multiple catches if there are multiple exceptions.

 3. Use the parent class Exception of the exception to catch the exception (when there are many exceptions in the program, and it is not clear what kind of exception)

All exception objects can be accepted and can be upcasted to Exception objects.

- Not recommended, can't troubleshoot

 4. Error output about exception

In Java, everything is an object, a null pointer, an array out of bounds, Exception -> is an exception, when a class generates an exception, the JVM will construct a corresponding (corresponding exception class) exception and pass it to the program.

 5. Regarding finally code blocks - code blocks that will be executed regardless of whether an exception is generated!

 Regarding the return value of the exception

Once finally has a return value, the return value equivalent to try and catch is invalid.

However, it is generally not recommended to write the return value in finally.

 6. Call chain about exception

The exception will continue to pass along the call chain until the exception is caught and handled. If the calling process does not handle the exception, the exception is finally thrown to the JVM, and the program is terminated.

7. JDK7 new automatic shutdown interface 

Once a class implements the AutoCloseable interface, it means that the class has the ability to automatically close – declare that the close method is automatically called in the try code block.

8.—Group keywords

throws: used in method declarations, it is clear that the method may generate the exception, but this exception is not handled, and is thrown back to the caller for processing.

Throw: used inside a method to artificially generate an exception object and throw it.

 

3. Exception Architecture

Error: Refers to the internal error of the program. This kind of error cannot be caught and handled by our programmers. Once an Error error occurs, the program can only inform the user that an error occurred, and the program exits directly.

StackOverflowError: Stack Overflow Error - generally occurs when the recursive call chain is too deep and the recursion has no exit

OutOfMemoryError: heap overflow Error

 Java's exception system is divided into two categories

1. Unchecked anomalies: The blue box in the left figure and its subclasses belong to unchecked anomalies. All unchecked exceptions do not force the program to use a try catch block. Error and RuntimeException (runtime exception, null pointer, type conversion, array out of bounds) and their subclasses are unchecked exceptions

2. Checked exceptions: The red boxes and their subclasses in the left picture are checked exceptions, except for non-checked exceptions, they are checked exceptions, and try must be displayed. . catch. . Exception handling, or throws. Exceptions other than Error and RuntimeExcpetion and their subclasses are checked exceptions and must be handled explicitly.

3. Custom exception class: During program development, there must be some errors related to specific business. It is impossible for JDK to provide corresponding exception classes for such errors. The defined exception class, if the user is required to force exception handling, inherit the Exception parent class - checked exception If the user does not need to display the processing exception, inherit the RuntimeException parent class - unchecked exception

4. [Write a code about login exception handling]

package object_oriented.exception;

import java.util.Scanner;

public class Login {
    public static String USER="浩民";
    public static String PASSWORD="123456";

    public static void main(String[] args) {
        try {
            login();
            System.out.println("登陆成功!!");
        }catch (UserNameException e){
            e.printStackTrace();
        }catch (PasswordException e){
            e.printStackTrace();
        }
    }

    //throws 用在方法声明上,明确表示该方法可能会产生异常,但是不处理该异常,抛给调用者处理
    private static void login() throws UserNameException{
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入用户名:");
        String user=scanner.next();
        System.out.println("请输入用户名密码:");
        String password=scanner.next();
        if(!USER.equals(user)){
            //throw 用在方法内部,人为产生异常对象并抛出
            throw new UserNameException("用户名错误!");
        }
        if(!PASSWORD.equals(password)){
            throw new PasswordException("用户名密码错误!");
        }
    }
}

//用户名异常
class UserNameException extends Exception{
    public UserNameException(String msg){
        super(msg);
    }
}

//用户名密码异常
class PasswordException extends RuntimeException{
    public PasswordException(String msg){
        super(msg);
    }
}

Guess you like

Origin blog.csdn.net/m0_62218217/article/details/122644732