Java exceptions are derived from an instance of the Throwable class, and all exceptions are inherited from Throwable. Throwable has Error classes and Exception classes.
The Error (Error)
The Error class hierarchy describes internal errors and resource exhaustion errors in a Java runtime system. Error represents a serious problem, usually an Error occurred during JVM runtime, An OOM error is raised when no memory is available, a StackOverflowError is raised, a Java Virtual machine running error is raised, or a NoClassDefFoundError is raised. If such an internal error occurs, nothing can be done except to notify the user and try to make the program terminate safely.
Exception
Exceptions are divided into runtimeExceptions and other exceptions. Exceptions caused by program errors are runtimeExceptions, and there is no problem with the program itself, but exceptions caused by problems such as I/O errors are other exceptions.
RuntimeException: As the name implies, an exception that may be thrown by the runtime and that the compiler does not handle. For example, array indexes are out of bounds, objects used are null, cast errors, division by 0, and so on. When a runtime exception occurs, it is usually a problem with the program’s logic, not external factors.
Other exceptions: All exceptions in Exception other than runtime exceptions are exceptions. Also known as compile-time exceptions, these are the exceptions that the compiler must handle. This part of the exception is usually caused by the external runtime environment, because the program may be running in various environments, such as opening a file that does not exist and throwing a FileNotFoundException. The compiler requires Java programs to catch or declare all compile-time exceptions, forcing programs to prepare for possible exceptions.
Don’t be fooled by the name of the runtime exception; theoretically all errors occur at runtime. This includes errors, RuntimeExceptions, compile-time exceptions, and so on. All of these can only be encountered while the program is running. Compile-time exceptions are exceptions that the compiler requires to be handled, not errors that occur between compilations of code.
Abnormal and untested
Literally, checked exceptions and unchecked exceptions. Based on the above information, neither Error nor RuntimeException runtime exceptions can be checked. Runtimeexceptions are usually the problem of the program logic itself. Checked exceptions are the above compile-time exceptions that are forced to be caught or declared at compile time. The compiler will provide exception handlers for all checked exceptions.
PS: In fact, the exception occurred, except to change the program or configuration, there is no other way. Errors and exceptions (run-time and compile-time exceptions) occur simply by classifying what causes a program to not work properly. This classification allows programmers to better locate the cause of such errors, making development easier and more efficient, and writing more robust code. But exceptions do not change the result of the current run, because the logic and data are fixed from the moment the program starts running.
Exception handling mechanism
The try-catch-finally and throw and throw keywords are mainly used.
Exceptions are derived from an instance of the Throwable class, which can be generated by the JVM or created manually in a program and thrown manually with a throw. The object of a throw must be an instance derived from a Throwable class; other types cannot be compiled.
There are only two options for detecting anomalies. Either it is captured and processed, or it is thrown and left to the caller. There is no such mandatory requirement for non-tested anomalies.
Throws is used to declare exceptions, as long as derived from a Throwable class can be declared. It is mandatory that a method declare all possible checked exceptions in its header. Non-checked exceptions are not required to be declared through throws, because there is nothing to be done about an Error after it occurs. If there is a runtime exception, it is the problem of the program itself and time should be spent on correcting the Error of the program rather than explaining the possibility of the program occurrence. Therefore, when writing a program, the throws concern is checked exceptions, but non-checked exceptions can also be declared through throws, but it is not mandatory. If there are more than one checked exception, you must declare them all in throws. If the method does not declare all possible checked exceptions, the compiler issues an error.
Try-catch-finally is used to catch exceptions. All classes derived from Throwable can be caught by a catch. If any code in the try block throws an exception class specified in the catch clause, the program skips the rest of the code in the try block. And executes the processor code in the catch clause. If the code in the try block does not throw any exceptions, the catch clause is skipped, and if any code in the method throws an exception type not declared in the catch clause, the method exits immediately.
Multiple exception types can be caught in a try block and handled differently for different types of exceptions. You can use a separate catch clause for each exception type. It is important to note that if the exception in multiple catches is non-inherited, the catch order does not affect the result. If the catch exception has a class inheritance relationship, the catch of the subclass should be placed first and the catch of the parent class should be followed. As shown in the figure below, the judgment of catch is from top to bottom. If the parent class comes first, all the processing code derived from the parent class will be caught and executed, so that the processing code of the later children will never be executed.
Finally is usually used to close occupied resources. If the code throws an exception, it terminates processing for the rest of the code and exits the method. This may cause some programs to occupy the system and not be released properly. The finally clause code is executed whether or not an exception is caught, and the resource is properly released here.
Grasp the cast model
All exceptions must have an instance and then be thrown. This can be done by JVM or manually. This instance is the source of the entire exception handling. The calling class can then use try-catch-finally to catch the exception or continue throwing it to the upper layer through throws at the method head. Try-catch-finally is a catch, and throw/throws is a throw. A class encounters an exception and either catches it after processing, or continues to throw it up for the caller to handle.
Catch can be empty so that the program ignores exceptions. Not processing is processing itself. Exceptions can also be thrown in a catch, or they can be thrown manually. This allows you to change the type of exception, use exception wrapping techniques, and allow the user to throw advanced exceptions in the subsystem without losing the details of the original exception.
Try-catch-finally can be combined flexibly. This can be try-catch, try-finally, or try-catch-finally. It can be divided into the following situations
1. The try command is executed properly, and the catch command is ignored.
2. If an exception occurs ina try and is declared ina catch, run the catch command and finally run the finally command.
3. If an exception occurs in the try file but is not declared in the catch file, the catch file is not executed and finally is executed.
4. If an exception occurs ina try and is declared ina catch, an exception occurs when a catch is executed, the code in the catch is stopped, finally is executed, and the new exception is thrown in the catch.
finally
Finally Whether there is no exception ina try or catch, it will most likely be executed. This is because the compiler makes two copies of the finally block and adds them after the try and catch, respectively. However, if a system.exit () statement is present ina try or catch, the System exits directly and the finally module is not executed.
There is no return statement in finally that returns a value of 2
Finally has a return statement that returns 3
The above two codes differ only in the presence or absence of a return statement in finally, but the direct result is different. You can see that if there is no return statement in finally, the program ignores manipulation data in finally. Data operations in finally are also performed, but are not returned. This is because before the return statement returns, the virtual machine pushes the value to be returned onto the operand stack and waits for it to return. Even if the finally block changes I, the value to be returned is already in the operand stack, so it does not affect the program’s return.
When a return statement is detected after processing data ina try, the finally statement is pushed onto the operand stack to wait for a return, and then the finally statement is executed. If the finally statement does not push the new result onto the operand stack, only the original result is returned. To put it this way, even though data is processed in finally, it still returns “dirty data” ina try. Finally is not not executed, but executed without returning. Adding a return statement pushes finally data into the operand stack and returns the original “dirty data”.
Note that this refers to the base variable, if the reference type is not affected. Because no matter where you do the calculation, you’re dealing with the “entity” behind the reference.
Throwable
Throwable is the top-level exception class. Here are the main methods of the Throwable class:
1.public String getMessage()
Returns detailed information about the exception that occurred. The message is initialized in the constructor of the Throwable class
2.public Throwable getCause()
Return a Throwable object representing the cause of the exception
3.public String toString()
Returns the string name of the class using the result of getMessage()
4.public void printStackTrace()
Prints the toString() result and stack hierarchy to System.err, the error output stream
5.public StackTraceElement [] getStackTrace()
Returns an array containing the stack hierarchy. The element with subscript 0 represents the top of the stack, and the last element represents the bottom of the method call stack
6.public Throwable fillInStackTrace()
Populates the Throwable object stack hierarchy with the current call stack hierarchy, adding to any previous information in the stack hierarchy
Custom exception
It is not possible for all exceptions defined in Java’s exception mechanism to anticipate all possible errors, and in certain situations, we need to define our own exception types to report up certain error messages.
In general, user-defined exception classes are subclasses of RuntimeException
Custom exception classes typically require writing several overloaded constructors
A customized exception requires a serialVersionUID unique ID for easy debugging
The most important thing to customize an exception is the name of the exception class. When an exception occurs, you can determine the type of the exception by the name
Matters needing attention
When a subclass overrides a function declared by its parent class with throws declaration, the declared exception scope must be within the scope supported by the parent class, that is, the scope must not be larger than the parent class. Just keep the range the same or more accurate, not bigger. If the parent class does not have throws, then the child class cannot have throws either. Checked exceptions must be caught and handled within the child class.
Java programs can be multithreaded. Each thread is a separate flow of execution, a separate stack of function calls. If the program has only one thread, exceptions that are not handled by any code cause the program to terminate. If it is multithreaded, exceptions that are not handled by any code simply cause the thread in which the exception was created to terminate. That is, exceptions in Java are thread-independent and should be handled by the thread itself, not delegated externally, and not directly affecting the execution of other threads.
If you are interested in learning more about the basics of programming, watch the instructional video to continue learning. Exception handling is no substitute for simple testing. The time it takes to catch an exception is much longer than the time it takes to test, so if possible, judge the execution condition first rather than catch an exception after the execution has gone wrong.