Interview question: Java must know and must know: detailed explanation of exception mechanism

1. Overview of Java exceptions 
In Java, all events can be described by classes, and exceptions in Java are described by exception classes under the java.lang package .

Java exception class

1. Throwable (throwable): The final parent class of the exception class, it has two subclasses, Error and Exception. 
Commonly used methods in Throwable are: 
getCause(): Returns the reason for throwing an exception. Returns null if the cause does not exist or is unknown. 
getMeage(): Returns the message information of the exception. 
printStackTrace(): The stack trace of the object is output to the error output stream as the value of the field System.err.

2, Error (error): Indicates an error that the program cannot handle, generally unrelated to the programmer's execution. In theory, these errors are not allowed to occur. If they occur, they should not be attempted to be handled by the program, so Error is not the processing object of try-catch, and the general processing method of JVM is to terminate the thread where the error occurred. Common subclasses of the Error class include VirtualMachineError and AWTError.

3. VirtualMachineError (virtual machine error): Indicates that an error has occurred in the virtual machine. 
In the Java runtime memory, the virtual machine stack, heap, and method area except the program counter will throw OutOfMemoryError when the requested memory cannot be satisfied; 
and if the stack depth requested by the thread exceeds the depth allowed by the virtual machine, an OutOfMemoryError will be thrown. Throws StackOverFlowError.

4. AWTError (AWT component error): This error is not very commonly used. But mention the difference between AWT and Swing. AWT is an abstract window tool that uses the graphics functions in the operating system. It is written in C\C++. In order to realize the concept of "compile once, run everywhere" in Java, AWT uses the graphics functions of each operating system.
The Swing component is a graphical interface system based on AWT, which is written in pure Java, so it must realize "compile once, run everywhere", but it is relatively  It runs slower than AWT and is suitable for PC use.

5. Exception: The cause of the occurrence depends on the program, so the program should also be handled by try-catch. 
There are two types of exceptions: checkable exceptions and unchecked exceptions.

Checkable exception: The compiler requires that it must be handled, otherwise it cannot be compiled , caught by try-catch or thrown by throws. Common checkable exceptions are IOException (IO error) and its subclasses EOFExcption (file has ended exception), FileNotFound (file not found exception).

Unchecked exceptions (also called runtime exceptions): They are not checked at compile time, so they may not be handled in the program, but if they occur, they will be thrown at runtime. So this kind of exception should be avoided as much as possible ! Common unchecked exceptions are the RuntimeException class and its subclasses .

1' NullPointerException: Null pointer exception. Thrown when a non-existing object or an object that has not been instantiated or initialized is called , such as when trying to manipulate a property or method of an empty object (assigned to null).

(Instantiation: The popular understanding is to open up space for the object so that it can be called within the specified scope. Note: User u; This is just an object declaration, and has not been instantiated or initialized. 
Initialization: is to instantiate the The basic data type field in the object is assigned a default value or a set value, and the non-basic type is assigned null, and the static field is only initialized once.)

2' ArithmeticException: Arithmetic condition exception. The most common is to throw when dividing by 0 .

3' ClassNotFoundException: Class not found exception. When obtaining a class by reflecting Class.forName("class name"), an exception will be thrown if it is not found .

4' ArrayIndexOutOfBoundsException: Array index out of bounds exception. Thrown when attempting to manipulate an array whose index value is negative or greater than or equal to the size of the array .

5' NegativeArraySizeException: Array length is negative exception. Generally thrown when initializing the array size to a negative value.

6' ArrayStoreException: Array type mismatch value exception. For example, when adding an Integer object and a String object to an Object array, the type mismatch will be thrown .

7' IllegalArgumentException: Illegal argument exception. It will be thrown when the passed parameter value is out of bounds when using the Java class library method.

2. 
Exception handling The principle of exception handling in Java: It is necessary to declare that an exception is thrown or catch a checkable exception, and it is allowed to ignore Error and unchecked exception.

public class TestException {
    public static void main(String[] args) throws IOException{ //抛出可查IO异常 //throw是针对对象抛出的异常,throws是针对方法抛出的异常 FileWriter fileWriter = new FileWriter("output.txt"); String str = null; //str对象未经初始化 try { fileWriter.write(str); //尝试调用未经初始化的str对象,会抛出空指针异常 } catch (NullPointerException e) { System.out.println("Catch NullPointerException!"); }finally{ str = "finally!"; fileWriter.write(str); fileWriter.close(); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Execution result: 
console:

Catch NullPointerException!

output.txt:

finally!

1. Throws means throwing. As long as an exception occurs, the corresponding exception object will be created, and then the exception information such as the running status at the time of the exception will be recorded and delivered to the runtime system for processing. Throwing an exception must be executed before catching, and there will be no catching if it is not thrown. Programs can explicitly use throws to declare that a checkable exception is thrown in order to pass compilation.

2. try-catch-finally exception capture statement: 
try is the program segment where exceptions may occur ;

The corresponding exception handler methods are written in sequence in catch. When an exception is thrown, the runtime system will check the methods in turn from the current position in the stack until a suitable exception handling method is found. If not found, execute finally or directly End program operation.

finally : The statements in the finally block will be executed regardless of whether the exception is caught or handled
Note (very important, frequently asked in interviews): When a return statement is encountered in a try block or catch block, the finally statement block will be executed before the method returns. 
In the following 4 special cases, the finally block will not be executed: 
1) An exception is thrown and unhandled in the finally statement block. 
2) In the previous code, System.exit() was used to exit the program. 
3) The thread where the program is located dies. 
4) The CPU is turned off abnormally.

3. The execution order of try-catch-finally 
1' When no exception is caught, the catch will be skipped and the finally block will be executed directly.

public class TestException {
    public static void main(String[] args){ try { System.out.println("Hello world!"); } catch (NullPointerException e) { System.out.println("Catch NullPointerException!"); }catch (ArithmeticException e) { System.out.println("Catch ArithmeticException!"); }catch(Exception e){ System.out.println("Catch other Exception!"); } finally{ System.out.println("Finally!"); } } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Output result:

Hello world! 
Finally!

2' When a runtime exception is thrown and the corresponding exception handling method is not defined, the exception will be thrown by the JVM.

public class TestException {
    public static void main(String[] args){ String str = null; int a = 2, b = 0; //调用空对象的方法,会抛出空指针异常 System.out.println(str.length()); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Output result:

Exception in thread “main” java.lang.NullPointerException 
at Java面试.TestException.main(TestException.java:11)

3. When try catches an exception, the exception is handled in the catch statement block: in the try statement block, it is executed in order. When an exception occurs in the execution of a statement, the program will jump to the catch statement block, and Match the catch statement blocks one by one and find the corresponding handler. Other catch statement blocks will not be executed, and in the try statement block, the statement after an exception will not be executed. After the catch statement block is executed, Finally execute the statement after the finally block.

public class TestException {
    public static void main(String[] args){ String str = null; int a = 2, b = 0; try { //调用空对象的方法,会抛出空指针异常 System.out.println(str.length()); //语句1 //除数为0,会抛出数学运算错误 System.out.println("a/b=" + a/b); //语句2 } catch (NullPointerException e) { System.out.println("Catch NullPointerException!"); }catch (ArithmeticException e) { System.out.println("Catch ArithmeticException!"); }catch(Exception e){ System.out.println("Catch other Exception!"); } finally{ System.out.println("Finally!"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Output result:

Catch NullPointerException! 
Finally!

3. Customize an exception class 
by inheriting the Exception class.

class MyException extends Exception { // 创建自定义异常类 String message; // 定义String类型变量 public MyException(String ErrorMessagr) { // 父类方法 message = ErrorMessagr; } public String getMessage() { // 覆盖getMessage()方法 return message; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4. Exception chain and exception stack trace

public class TestException {
    public static void main(String[] args){ TestException test = new TestException(); String str = null; test.printStringMessage(str); } public void printStringMessage(String str){ System.out.println(str.length()); } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Exception in thread “main” java.lang.NullPointerException 
at Java面试.TestException.printStringMessage(TestException.java:16) 
at Java面试.TestException.main(TestException.java:12)

Regular exceptions: There are exceptions defined by Java, and no exception declaration is required. If there is no try-catch, it will be reported to the main() method by default.

Exception bubbling upload mechanism: When an exception object is generated, it will bubble according to the calling level (usually the calling level of the method) until it is processed by try-catch or reported to the main() method.

//自定义的异常类
public class MyException extends Exception{ String message; // 定义String类型变量 public MyException(String ErrorMessagr) { // 父类方法 message = ErrorMessagr; } public String getMessage() { // 覆盖getMessage()方法 return message; } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
//测试异常链、冒泡机制
public class TestException {
    void firstThrow() 
            throws MyException { //抛出自定义异常 System.out.println("Oringinally creat a MyException and throw it out"); throw new MyException("MyException"); //真正的抛出异常处 } void secondThrow() throws MyException { //抛出自定义异常 firstThrow(); //调用firstThrow() } public TestException() throws MyException { //构造方法,抛出自定义异常 secondThrow(); //调用secondThrow() } public static void main(String[] args) { try{ //调用构造方法 TestException testException=new TestException(); } catch(MyException e) { e.printStackTrace(); System.out.println("Catch a my exception!"); } } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Output result:

Oringinally creat a MyException and throw it out 
Java面试.MyException: MyException 
at Java面试.TestException.firstThrow(TestException.java:11) 
at Java面试.TestException.secondThrow(TestException.java:16) 
at Java面试.TestException.(TestException.java:20) 
at Java面试.TestException.main(TestException.java:26) 
Catch a my exception!

From the record information of the exception stack, it can be found that the exception throwing mechanism and order corresponding to the code:

firstThrow() generates a MyException object -> the exception bubbles up to the secondThrow() that calls it -> bubbles up to the constructor of the TestExceptionChain that calls secondThrow() -> bubbles up to the main() method of printtry.

Note: The exception object has been thrown until it is caught by try-catch in the main() method of printtry!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325314107&siteId=291194637