[advanced Java] exception

Exception refers to the abnormal situation that occurs during the execution of the program, which will eventually lead to the abnormal stop of the JVM.

In object-oriented programming languages such as Java, the exception itself is a class. Generating an exception is to create an exception object and throw an exception object. The way Java handles exceptions is interrupt handling. An exception does not refer to a syntax error. If the syntax is wrong and the compilation fails, a bytecode file will not be generated and cannot run at all.

1, Abnormal system

Error: serious error, which cannot be solved by the Java virtual machine and can only be avoided in advance. Common errors include virtual machine error, out of memory error and thread death.

Exception: indicates an exception. General problems caused by programming errors or accidental external factors can be treated as targeted code. It is divided into UncheckedException and CheckedException. Non check exceptions can be ignored, and check exceptions must be caught or declared to be thrown.

The runtime Exception refers to Java Lang. runtimeException class and its subclasses. Compile time Exception refers to the subclass of Exception class and other exceptions excluding runtime exceptions.

The exception mechanism actually helps us find problems in the program. The root class of the exception is Java Lang. throwable, which has two subclasses: Java Lang. error and Java Lang. exception, the usual exception refers to Java lang.Exception.

2, Common runtime exceptions

Null pointerexception null pointer exception: this exception is thrown when an application attempts to use null where an object is needed.

For example, call a null referenced variable to call the method:

Object obj = null;
System.out.println(obj.hashCode());

ArithmeticException mathematical operation exception: this exception will be thrown when an abnormal operation condition occurs.

For example, when an integer is divided by 0:

int i = 10 / 0;

ArrayIndexOutOfBoundsException array subscript out of bounds exception: an exception that runs out when accessing the array with illegal. If the index is negative or greater than or equal to the size of the array, an exception is thrown.

For example, an array has only three elements, and the index should be 0,1,2, but when accessing the element with index 3:

int[] arr = new int[3];
arr[3] = 10;

ClassCastException type conversion exception: this exception is run when trying to cast an object to a subclass that is not an instance.

For example, class A is the parent of class B and class C, but there is no inheritance relationship between class B and class C. when converting the object of class B to class C:

public class ExceptionTest {
    public static void main(String[] args) {
        A a = new B();
        C c = (C) a;
    }
}

class A {}
class B extends A {}
class C extends A {}

3, Exception handling

Five keywords of Java exception handling: try, catch, finally, throw, throws

3.1 catch exception try catch finally

The way of try catch is to catch exceptions. Targeted statements in Java can catch exceptions, and the exceptions can be handled in a specified way.

try: write code that may cause exceptions in this code block.
Catch: it is used to catch certain exceptions and handle the caught exceptions.
finally: there are some specific codes that need to be executed whether an exception occurs or not.

Syntax format:

try{
    // Catch exception
    // Write code that may cause exceptions 
}catch(Exception type exception variable name){  
	// When an exception occurs, the system encapsulates the exception into the object of the formal parameter and passes it to the catch block
	// Then deal with the caught exceptions according to your own needs
	// Log / print exception information / continue to throw exceptions, etc
}finally{
	// Execute whether there is an exception or not
}

① try block can be followed by zero or more catch blocks. If there is no catch block, it must be followed by a finally block. try, catch and finally cannot be used alone. They must be used together.

In this way, if there is an exception, the result is the same as that of not capturing the exception, and the program will collapse directly

try {
    System.out.println("Can not catch block");
} finally {
    System.out.println("without catch Block, there must be finally block");
}
try {
    System.out.println("Or not finally block");
} catch (ClassCastException e) {
    // There can be multiple catch blocks
    System.out.println("first catch block");
} catch (NullPointerException e) {
    System.out.println("the second catch block");
}

② If there are multiple catch clauses, the parent exception is required to be in the back and the child exception is required to be in the front. And if an exception is encountered, multiple catch blocks will only match the nearest one.


Because the exception will cause program jump, resulting in some statements can not be executed, so

③ The code stored in the finally code block is bound to be executed.

For example, if some physical resources (disk file / network connection / database connection, etc.) are opened in the try statement block, the open resources must be closed after use. Generally, these codes are placed in the finally code block.

④ If finally has a return statement, always return the result in finally to avoid this situation.

When try or catch is called to exit the relevant methods of JVM, finally will not execute at this time, otherwise finally will always execute. Method of terminating JVM: system Exit (non-zero number);

Execute the following code to see that the result is 3:

public class ExceptionTest {
    public static void main(String[] args) {
        System.out.println(getI());
    }

    public static int getI(){
        try {
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            return 3;
        }
    }
}

3.2 declare exception throws

The keyword throws is used on the method declaration to indicate that the current method does not handle exceptions and remind the caller of the method to handle exceptions (throw exceptions). If the method may have multiple exceptions, you can write multiple exception classes after throws, separated by commas.

It is generally used when an exception may occur in a method, but it is uncertain how to handle the exception, then the method can declare to throw an exception.

Syntax format:

Modifier return value type method name(parameter) throws Exception class name 1,Exception class name 2 {   
} 

When a subclass overrides the method that the parent class throws an exception, the declared exception must be the same kind or subclass of the exception declared by the parent class method.

public static void main(String[] args) throws IOException {  
	read("a.txt");  
}

public static void read(String path) 
    throws FileNotFoundException, IOException {  
	if (!path.equals("a.txt")) {   
		// Suppose that if it is not a.txt, it is considered that the file does not exist and an exception is thrown
		throw new FileNotFoundException("file does not exist");  
	}  
	if (!path.equals("b.txt")){  
		throw new IOException();  
	}  
}  

① If you don't catch an exception and keep declaring an exception, it will eventually be handled by the JVM. The JVM's handling method is to output exception information and exit the program.

If an exception is found, output the exception information and exit the program

② For compile time exceptions, they must be handled in the program. Try catch or throws can be used

If it is not handled, an error will be reported.

You can declare it on the method:

Try catch can also be used to solve the problem:

③ For runtime exceptions, if they are not handled in the program, throws XXXException will be declared by default

④ If the parent class throws multiple exceptions, when overriding the parent class method, the child class can throw the same exception as the parent class, the child class of the parent class exception, and do not throw an exception.

The following classes B, C and D can be compiled:

class A {
    public void m1() throws IOException, SQLException {}
}

class B extends A {
    @Override
    public void m1() throws IOException {}
}

class C extends A {
    @Override
    public void m1() {}
}

class D extends A {
    // FileNotFoundException is a subclass of IOException
    @Override
    public void m1() throws FileNotFoundException {}
}

⑤ The parent class method does not throw an exception. When the child class overrides the parent class method, it cannot throw an exception. It can only be caught and processed, and cannot be declared to throw.

So you can't compile

4, throw exception

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. Throw can only throw instance objects of the class Throwable or its subclasses.

Syntax format:

// Throw it yourself and handle it by the caller
 Return value method name(parameter) throws Exception class name{
	throw new Exception class name(parameter);  
}
// Throw it out and deal with it yourself
try{
	// Code block 1
    throw new Exception class name(parameter);
} catch (Exception class name variable name){
	// Code block 2
}

If a problem occurs, throw will throw the exception, that is, return the problem to the caller. The caller can do capture processing or use throws declaration processing.

public static void main(String[] args) {  
	//Create an array  
	int[] arr = {2,4,52,2};  
	//Find the corresponding element according to the index  
	int element = getElement(arr, 4);  
	System.out.println(element);  
}

/* 
* Find the corresponding element in the array according to the index 
*/  
public static int getElement(int[] arr, int index){  
	//Judge whether the index is out of bounds  
	if(index < 0 || index > arr.length‐1){  
		/*
        If the judgment conditions are met, the method cannot continue operation after throw ing the exception object,
        It ends the execution of the current method and notifies the caller of the exception.
		*/  
		throw new ArrayIndexOutOfBoundsException("Man, the corner marker is out of bounds~~~")  
	}  
	int element = arr[index];  
	return element;  
}

5, Custom exception class

Using the built-in exception class in Java can describe most of the exceptions that occur during programming, and you can also describe the exception types generated by specific businesses through custom exceptions.

Custom exception class: define a class to inherit Throwable class or its subclasses.

Define compile time exception: inherited from Java lang.Exception.
Define run-time exceptions: inherited from Java lang.RuntimeException.

 // Business logic exception  
 public class RegisterException extends RuntimeException{  
     /** 
     * Empty parameter structure 
     */  
     public RegisterException() {  
     }  
     
    /** 
     * Parametric structure
     * @param message Indicates an exception prompt 
     */  
     public RegisterException(String message) {  
         super(message);  
    }  
 }  

6, The difference between throw and throws

describeUse locationCode followed
throwThrow an exception and manually generate the keyword of an exception objectMethod bodyException object
throwsA way of exception handlingMethod declaration OfficeException type

Keywords: Java Back-end

Added by justspiffy on Wed, 09 Feb 2022 01:43:43 +0200