Java study notes 12 exception handling

abnormal

Exceptions refer to abnormal events that occur during the running of a program, usually caused by external problems (such as hardware errors, input errors). In object-oriented programming languages ​​such as Java, exceptions belong to objects.

Java exception handling: try catch finally throw thorws exception superclass java.lang.Exception

Exceptions are all runtime. What is generated at compile time is not an exception, but an error (Error).

Errors caused by initial programming are not exceptions.

However, Error is generally regarded as a type of exception, so exceptions are generally divided into two categories, Error and Exception.

exception type illustrate
Exception The root class of the exception hierarchy
RuntimeException runtime exception, the root class of most java.lang exceptions
ArithmeticException Arithmetic spectrum error exception, such as dividing by zero
ArraylndexOutOfBoundException The array size is smaller or larger than the actual array size
NullPointerException Attempt to access null object member, null pointer exception
ClassNotFoundException A required class could not be loaded
NumberF ormatException The number conversion format is abnormal, such as the conversion of a string to a float number is invalid
IOException Root class for I/O exceptions
FileNotFoundException file not found
EOFException end of file
InterruptedException thread interrupt
IllegalArgumentException The method received an illegal parameter
ClassCastException type conversion exception
SQLException Operation database exception

try{
}catch (NumberF ormatException) {
} catch (InputMismatchException e) {
} catch (Exception e) {
} finally{
}

A program can throw a variety of exceptions. When an exception is thrown, Exception is the general exception class. It is recommended to write it at the end of the exception.

We can also define exception classes ourselves.

insert image description here
insert image description here
In exception handling, throw is an artificially thrown exception that generally appears in the try{block} and is caught by catch.

Throws generally appear after the method declaration, indicating that there is an exception in the current method, and there is no try to handle it, and it is thrown. Whoever calls this method will handle it. If it is not handled, it will be thrown on the method.

finally block execution

Applied after try{}catch(){}, it means a block of code that must be executed regardless of whether there is an exception.

Make some optimizations to the number guessing game using exception handling.

 public static void main(String[] args) {
    
    
        Random rand = new Random();
        Scanner sc = new Scanner(System.in);
        int[] level = {
    
    10, 20, 30, 40, 50};
        int le = level[rand.nextInt(0, 5)];
        int sucess = rand.nextInt(1, le);
        int great = 0;
        int a = 0;
        while (true) {
    
    
            System.out.printf("请输入一个[1-%d]的整数\n", le);
            try {
    
    
                a = sc.nextInt();
            } catch (InputMismatchException e) {
    
    
                if ("exit".equals(sc.next())) {
    
    
                    break;
                }
                System.out.println("输入的字符不合法,请输入整数");
                continue;
            }
            if (a < 1 || a > le) {
    
    
                System.out.printf("输入的数不在[1-%d]上\n", le);
                continue;
            }
            if (a > sucess) {
    
    
                great++;
                System.out.println("\033[031m猜大了\033[0m");
            } else if (a < sucess) {
    
    
                great++;
                System.out.println("\033[031m猜小了\033[0m");
            } else {
    
    
                System.out.printf("\033[032m猜对了\033[0m,成绩为\033[031m%d\033[0m", 100 - great * 5);
                break;
            }
        }
The difference between final, finally and finalize
1. Simple difference:

final is used to declare attributes, methods, and classes, respectively indicating that attributes cannot be changed (constant), methods cannot be overridden, and classes cannot be inherited.
finally is part of the exception handling statement structure, which means it is always executed.
finalize is a method of the java.lang.Object class. When the garbage collector executes, it will call this method of the reclaimed object for other resource recovery during garbage collection, such as closing files.

2. Moderate difference:

Although this word exists in Java, it doesn't have much connection:
final: keyword and modifier in java.
A). If a class is declared final, it means that it can no longer derive new subclasses and cannot be inherited as a parent class. Therefore, a class cannot be declared abstract and final at the same time.
B). If you declare variables or methods as final, you can guarantee that they will not be changed during use.
  1) Variables declared as final must be given an initial value at the time of declaration, and can only be read in subsequent references, Unchangeable.
  2) The method declared final can only be used and cannot be overloaded.
finally: an exception handling mechanism of java.
  finally is the best complement to the Java exception handling model. The finally structure makes the code always execute regardless of whether an exception occurs. Using finally can maintain the internal state of the object and can clean up non-memory resources. Especially in terms of closing the database connection, if the programmer puts the close() method of the database connection in finally, it will greatly reduce the chance of program errors.
finalize: A method name in Java.
Java technology uses the finalize() method to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector on this object when it determines that this object is not referenced. It is defined in the Object class, so all classes inherit it. Subclasses override the finalize() method to organize system resources or perform other cleanup tasks. The finalize() method is called on the object before the garbage collector deletes the object.

Guess you like

Origin blog.csdn.net/xxxmou/article/details/129169715