Understand what is a Java exception-Java study notes

Exception overview

A Java exception refers to a situation that is inconsistent with the normal situation during the execution of the program. At this time, it will eventually cause the JVM to stop abnormally.

In our programming process, we always encounter Java error reporting, and this error reporting is usually called an exception. In fact, this is in object-oriented programming languages ​​such as Java. The exception itself is a class. To generate an exception is to create an exception object and throw an exception object.

Anomaly classification

The root class of the exception is java.lang.Throwable, which has two subclasses: java.lang.Error and java.lang.Exception,
Insert picture description here

Checked Exception
is a checkable exception, which is very commonly used when coding. All checked exceptions need to be handled in the code. Their occurrence is predictable, and a normal situation can be handled reasonably. Such as IOException, or some custom exceptions. Except for RuntimeException and its subclasses, all are checked exceptions.

RuntimeException
means that the compiler will not check whether the program has processed RuntimeException. It is not necessary to catch RuntimeException type exceptions in the program, nor does it need to declare the RuntimeException class in the method body. When RuntimeException occurs, it means that there is a programming error in the program, so you should find the error and modify the program instead of catching the RuntimeException.

Several common exceptions and the reasons for this exception

1, java.lang.NullpointerException (Null pointer exception)

Reason: This exception is often encountered. The reason for the exception is that there is a null pointer in the program, that is, an uninitialized object or a non-existent object is called in the program. It often occurs in the code of creating objects and calling arrays, such as the object is not initialized, or the path when the image is created is wrong, etc.

2. java.lang.ClassNotFoundException (the specified class does not exist)

Reason: When trying to convert a String type data into a specified numeric type, but the string does not meet the requirements of numeric data, this exception is thrown. For example, when converting String type data "123456" into numeric type data, it can be converted. But if the String type data contains non-numeric characters, such as 123*56, an exception will occur when converted to numeric type. The system will catch this exception and deal with it

3. java.lang.ClassNotFoundExceptio (the specified class does not exist)

Reason: because the name and path of the class are incorrect, usually when the program tries to load a certain class through a string, an exception may be thrown. For example: an exception occurs when calling Class.forName(), or calling ClassLoadfinaSystemClass(), or LoadClass()

4. java.lang.IndexOutOfBoundsException (array subscript out of bounds exception)

Reason: Check whether the subscript value of the array or string called in the program exceeds the range of the array. Generally speaking, it is not easy to make such an error when displaying the calling array, but the implicit call may make an error. In this case, the length of the array defined in the program is determined by some specific method, not declared in advance. At this time, you can check the length of the array first to avoid this exception

5. java.lang.IllegalArgumentException (method parameter error)

For example, if there are three values ​​in the g.setColor(int red, int green, int blue) method, this exception will occur if there are more than 255. If this exception exists in the program, check the parameter passing in the method call Or parameter value is wrong

6, java.lang.IllegalAccessException (no access permission)

This exception occurs when the program wants to call a class, but the current method does not have access to the class. This exception may occur if Package is used in the program

7, java.lang.ArithmeticException (mathematical operation exception)

Such an anomaly occurs when there is an operation such as dividing by zero in a mathematical operation.

8, java.lang.ClassCastException (data type conversion exception)

This exception occurs when trying to force down conversion of an object, but the object is neither convertible nor convertible to an instance of its subclass

9. java.lang.FileNotFoundException (file not found exception)

This exception will be raised when the program opens a file that does not exist for reading or writing. This exception is thrown by the constructor declaration of FileInputStream, FileOutputStream, RandomAccessFile, even if the file being operated exists, but it is not accessible for some reason, such as opening a file with read-only permission and writing data to it, the above construction method is still Will throw an exception

10. java.lang.ArrayStoreException (array storage exception)
when trying to store an object of an incompatible type into an Object[] array, an exception will be thrown

11. java.lang.NoSuchMethodException (the method does not exist exception)
When the program tries to create an object through reflection, access (modify or read) a method, but the method does not exist, an exception will be thrown.

12. java.lang.EOFException (file end exception)
when the program encounters the end of the file or stream during the input process, an exception is thrown. So this exception is used to check if the end of the file or stream is reached

13. java.lang.InstantiationException (instantiation exception)
is raised when trying to create an instance of a certain class through the newInstance() method of Class, but the program cannot create the object through the constructor. The Class object represents an abstract class, interface, array class, and basic type. The class represented by this Class has no corresponding constructor.

14. java.lang.InterruptedException (aborted exception) is thrown
when a thread is in a long waiting, dormant or other suspended state, while other threads terminate the thread through the interrupt method of Thread.

15. java.lang.CloneNotSupportedException (clone exception is not supported)
When the Cloneable interface is not implemented or the clone method is not supported, calling its clone() method will throw the exception

16. java.lang.OutOfMemoryException (out of memory error) is thrown when the available memory is not enough for the Java virtual machine to allocate to an object

17. java.lang.NoClassDefFoundException (Class definition not found error)
This error is thrown when the Java virtual machine or class loader tries to instantiate a class, but the definition of the class cannot be found

Exception handling: catch and throw model

Process 1:
"Throw":
In the normal execution of the throw throws keyword program, once an exception occurs, a corresponding exception class object will be generated at the exception code, and after the object is thrown, the following The code is no longer executed.
Process two:
"catch": exception handling: try-catch-finally

throw keyword

Role:
It is used to throw a specified exception object. Throw is used in a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.
Use format:

throw new 异常类名(参数);
throw new NullPointerException("要访问的arr数组不存在");
throw new ArrayIndexOutOfBoundsException("该索引在数组中不存在,已超出范围");

throws keyword declaration to handle exceptions

Declare processing exception :
Use the throws keyword to identify the problem, which means that the current method does not handle the exception, but instead reminds the caller to handle it... Eventually, the virtual machine will end the program directly and print the exception information.
Use format:

修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2…{ 
 // 可以抛出一个,也可以多个。
}	

Use of try-catch-finally

Code:

try{
    可能会出现异常的代码
}catch(异常的类型 变量名){
    处理异常的代码
    //记录日志/打印异常信息/继续抛出异常
}finally{
    无论异常是否发生,都会执行这里的代码
    (正常情况,都会执行finally中的代码,一般用来释放资源)
}

Execution steps:
1. First execute the code in try. If there is an exception in the code in try, then directly execute the code in catch(). After execution, the code in finally will be executed, and then the program will continue to execute

2. If there is no exception in the code in try, then the code in catch() will not be executed, but the code in finally will still be executed, and then the program will continue to execute

Note:
1.finally is optional, it is not necessary to write.
2. Use try to wrap the possible exception code. During the execution, once an exception occurs, a team corresponding to the exception class object will be generated.
According to the exception type of this object, go to catch for matching.
3. Once the exception object in the try matches a catch, it enters the catch and continues to handle the exception.
Once the processing is completed, it jumps out of the current try-catch structure (without writing finally). Continue to execute the following code
4. If the exception type in
catch does not have a child-parent relationship, it does not matter who declares the exception type in catch. If the child-parent relationship is satisfied, the child class must be declared above the parent class, otherwise Report an error.
5. Commonly used exception object solutions: String getMessage() printStackTrace()
6. Variables declared in the try structure cannot be called after the try structure is released.
7. The try-catch-finally structure can be nested

Custom exception

What is a custom exception class:

Define the exception class according to the abnormal situation of your own business during development.

Customize a business logic exception: RegisterException . A registered exception class.

How to define the exception class:
Customize a compile-time exception: Customize the class and inherit from java.lang.Exception.
Customize a runtime exception class: custom class and inherit from java.lang.RuntimeException.

Custom exception exercise
Requirement: We simulate the registration operation, if the user name already exists, an exception will be thrown and prompt: dear, the user name has been registered.

First define a registered 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(LoginException e){
            //处理异常
            e.printStackTrace();
        }
    }

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

Guess you like

Origin blog.csdn.net/LinKin_Sheep/article/details/109329938