Java exception handling

Java exception handling

Overview of exceptions:

In the process of life and learning, many things are beyond our control. Life is full of surprises (anomalies)

  • For example: I think after half a month of learning Java, I suddenly launched a fun game... Disrupted my original plan and produced another result

In the process of project development using computer language, even programmers write the code perfectly

  • Some problems will still be encountered during the operation of the system, because many problems can not be avoided by code
  • For example, the format of customer input data, whether the read file exists, whether the network is always unobstructed, etc.

Exception: in the Java language, abnormal conditions during program execution are called "exceptions" (syntax errors and logic errors during development are not exceptions)

Exception architecture

The abnormal events that occur during the execution of Java programs can be divided into two categories:
Error: a serious problem that cannot be solved by the Java virtual machine

  • Such as: JVM system internal error, resource exhaustion and other serious situations
  • StackOverflowError and OOM generally do not write targeted code for processing.

Exception: for other general problems caused by programming errors or accidental external factors, targeted code can be used to deal with things considered by Java developers

  • For example:
    Null pointer access, trying to read a nonexistent file, network connection interrupted, array subscript out of bounds
    For these exceptions, we can capture and handle them. We try our best to deal with the possible exceptions in the development process!
    Otherwise, if it is released directly without processing, an exception will cause the program to report an error and collapse, resulting in the immediate end of the program (extremely poor user experience!!

Throwable is the top-level parent class

Some general exceptions are built in the Java standard pants. These classes take Throwable as the top-level parent class, and Throwable derives Error class and Exception class
Java program developers need to pay attention to: Exception exception!

Exception:

Exception s are divided into two categories:
Runtime exception:

  • Refers to an exception that the compiler does not require forced handling. Generally, it refers to the logic error in programming, which is an exception that programmers should actively avoid
  • Java.lang.RuntimeException class and its subclasses are runtime exceptions
  • We can write code to handle such exceptions (try... catch... finally) or not,
  • For these exceptions, we should modify the code instead of handling them through the exception handler. The reason for such exceptions is mostly the problem of writing the code.
  • Except:
    Except 0 error ArithmeticException
    Bad cast type ClassCastException
    Array index out of bounds ArrayIndexOutOfBoundsException
    Null object NullPointerException, etc. used

Compile time exception:

  • An exception that the compiler requires to be handled. That is, the general exception caused by external factors when the program is running
  • The compiler requires that Java programs must catch or declare all compile time exceptions
  • For this kind of exception, if the program does not handle it, it may bring unexpected results.
  • Javac forces programmers to prepare for such exceptions:
    (use try... Catch... finally or throws) in the method, either capture it with a try catch statement and process it, or throw it with a throw clause declaration, otherwise the compilation will not pass
    Such exceptions are generally caused by the running environment of the program.
    Because the program may be run in various unknown environments, and the programmer cannot interfere with how the user uses the program written by him, the programmer should be prepared for such exceptions
    For example:
    Sqlexception, IOException, classnotfoundexception, etc

Common Java exceptions:

Throwable class: All exception type superclasses are Error/Exception
	Error class: A serious error that cannot be recovered by the program itself. A virtual machine error in addition to making the program exit safely,There's nothing else I can do
	Exception class: Java The application throws a non critical error for processing. Molecular classes are: Runtime exception/Check for abnormalities( RuntimeException/Checked)
			RuntimeException Class stack: Runtime exception;
				It is not required that the program must deal with it,If an exception occurs,It will output exception stack information and abort the program
				Common error types:
					ArithmeticException				Arithmetic error condition,If you divide by zero, you get infinity: 2/0;  Or 2%0 Will report an exception: / by zero (An error is reported when dividing or dividing 0;) 
					ArrayIndexOutOfBoundsException	subscript out of bounds
					NullPointerException			Try to access null Object member
					IllegalArgumentException		Method received an illegal parameter
					ClassCastException				Object cast error
					NumberFormatException			Digital format conversion exception,Ru Ba"abc"Convert to number
					..............
			Checked	class: Check for abnormalities(An error is reported during compilation,Need to deal with)
				The program must catch or declare to throw such an exception, otherwise the compilation error;
					Exception						Parent of exception hierarchy
					SQLException					Database link...
					ClassNotFoundException			The required class could not be loaded

ArrayIndexOutOfBoundsException array subscript out of bounds

public class IndexOutExp {
    public static void main(String[] args) {
        String friends[] = { "lisa", "bily", "kessy" };
        for (int i = 0; i < 5; i++) {
        	System.out.println(friends[i]); // friends[4]?
        }
        System.out.println("\nthis is the end");
    }
}

Null pointerexception null pointer

public class NullRef {
    int i = 1;
    public static void main(String[] args) {
        NullRef t = new NullRef();
        t = null;
        System.out.println(t.i);
    }
}

ArithmeticException mathematical calculation exception:

public class DivideZero {
    int x;
    public static void main(String[] args) {
        int y;
        DivideZero c=new DivideZero();
        y=3/c.x; 
        System.out.println("program ends ok!");
    }
}

ClassCastException type conversion exception:

public class Order {
    public static void main(String[] args) {
        Object obj = new Date();
        Order order;
        order = (Order) obj;
        System.out.println(order);
    }
}

Exception handling mechanism:

Exception handling:
In order to avoid exceptions in the process of program execution, some processing methods for the code that may have exceptions are figured out in advance, and the exceptions that may be sent are captured and processed in advance!
Avoid program errors, resulting in the end of the program!

if -else

  • For exception handling, we can also directly use: if else to capture and handle!
  • Before each operation, judge whether the object is null and whether the divisor is 0... However, too many if else branches will lead to long, bloated and poor readability of the program code. Therefore, the exception handling mechanism is adopted

Introduction:

Java provides a catch and throw model for exception handling

  • If an exception occurs during the execution of a Java program, an exception class object will be generated
    The exception object will be submitted to the Java runtime system. This process is called throwing an exception.
  • Generation of exception objects
    The generation of exception objects is automatically generated by the virtual machine:
    During the running of the program, the virtual machine detects a problem with the program. If the corresponding handler try catch finally is not found in the current code
    An instance object corresponding to the exception class will be automatically created in the background and thrown -- automatically thrown
  • Manually created by the developer:
    Exception exception = new ClassCastException();
    If the created exception object is not thrown, it will have no impact on the program. Like creating an ordinary object, it is equivalent to new an exception object;
    throw exception throw program exception manually!
    throw new ClassCastException(); Anonymous object throws program exception!

try - catch - finally

try - catch

Catch (multiple)

  • Each catch() determines the handling methods for handling different errors and exceptions with different classes
  • However, the order must be from child to parent. The parent class of all exceptions inherits from: Exception class

Put the code with possible exceptions into: try - catch to catch exceptions. If exceptions occur, the program will find the code executed in the corresponding catch according to the exception type

try{
	//Possible exception codes
}catch(Exception class parameters e  ){  
	//The type used to catch exceptions, which cannot be caught by this type;
	system.out.print(e.getMessage());	// Console output!
	e.printStackTrace();  				// Print the exception stack information. If the program ends abnormally, you can also output a statement to prompt the user;
}catch( Exception e ){
	//The last one is because this is the parent class of all exception classes. If you put it first, each exception will be implemented, so you can't judge the specific error
	//And the system will compile errors
}

try - catch - finally

Program exception, the program will end!
The statement in finally will be executed anyway unless the server explodes or the virtual machine end method is used!

  • Even if return appears in try{} catch() {}, it will not exit! The operation in finally will be executed before the return is executed!

Finally can also be used for:

  • The Socket JVM in database connection I / O stream network programming will not be recycled automatically. We need to release resources manually! It can be declared that resource recycling is finally guaranteed!

finally, the only case in which a block statement is not executed is when the exception handling code executes system Exit (1) exit the java virtual machine
In the try - catch - finally structure, try is required and catch/finally is optional, but at least one of the two must appear
try - catch - finally belongs to the code block, the internal object belongs to the local variable, and the public variable should pay attention to the declaration position!

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.junit.Test;

/*
 * 1, Exception handling: grab and throw model
 * Process 1: "throwing": once an exception occurs during the normal execution of the program, an object corresponding to the exception class will be generated at the exception code.
 *           And throw this object.
 *           Once the object is thrown, the subsequent code is no longer executed.
 * 		Generation of abnormal objects: ① abnormal objects automatically generated by the system
 * 					 	 ② Manually generate an exception object and throw it
 * 
 * Process 2: "catch": it can be understood as the exception handling method: ① try catch finally ② throws
 
 * 2, Use of try catch finally 
 * try{
 * 		//Possible exception codes
 * }catch(Exception type 1 (variable name 1){
 * 		//How to handle exceptions 1
 * }catch(Exception type 2 (variable name 2){
 * 		//How to handle exceptions 2
 * }catch(Exception type 3 (variable name 3){
 * 		//How to handle exceptions 3
 * }
 * ....
 * finally{
 * 		//Code that must execute
 * }
 * 
 * explain:
 * 1. finally Is optional.
 * 2. try is used to wrap the possible exception code. In case of an exception during execution, an object corresponding to the exception class will be generated. According to the type of this object, it will be matched in catch
 * 3. Once the exception object in the try matches a catch, it enters the catch for exception processing. Once the processing is completed, it will jump out of the current try catch structure (without writing finally). Continue to execute the subsequent code
 * 4. catch If the exception type in has no child parent relationship, it doesn't matter who declares it on and who declares it under. If the exception type in catch satisfies the child parent relationship, the child class must be declared on the parent class. Otherwise, an error is reported
 * 5. Common exception object handling methods: ① string getmessage() ② printStackTrace()
 * 6. Variables declared in the try structure cannot be called after the try structure is created
 * 7. try-catch-finally Structures can be nested
 * 
 * Experience 1: use try catch finally to handle compile time exceptions, so that the program will no longer report errors at compile time, but errors may still be reported at run time.
 *       It is equivalent to using try catch finally to delay an exception that may occur during compilation until it occurs at run time.
 *     
 * Experience 2: in development, since runtime exceptions are common, we usually don't write try catch finally for runtime exceptions.
 *       For compile time exceptions, we say we must consider exception handling.
 */
public class ExceptionTest1 {

	@Test
	public void test1(){
		
		String str = "123";
		str = "abc";
		int num = 0;
		try{
			num = Integer.parseInt(str);
			
			System.out.println("hello-----1");
		}catch(NumberFormatException e){
//			System.out.println("there is a numerical conversion exception, don't worry...);
			//String getMessage():
//			System.out.println(e.getMessage());
			//printStackTrace():
			e.printStackTrace();
		}catch(NullPointerException e){
			System.out.println("There is a null pointer exception. Don't worry....");
		}catch(Exception e){
			System.out.println("There's something unusual. Don't worry....");
			
		}
		System.out.println(num);
		
		System.out.println("hello-----2");
	}

	@Test
	public void test2(){
		//try - catch - finally belongs to the code block, the internal object belongs to the local variable, and the public variable should pay attention to the declaration position!
		FileInputStream fis = null;
		try {
			File file = new File("hello1.txt");
			fis = new FileInputStream(file);
			
			int data = fis.read();
			while(data != -1){
				System.out.print((char)data);
				data = fis.read();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(fis != null)
					fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

Try catch finally can be nested to contain

Information about catching exceptions:

Like other objects, you can access the member variables of an exception object or call its methods to get exception information

  • printStackTrace(); void returns no value. The method internal output exception stack information is usually invoked in catch.
  • getMessage(); String return value returns the string new Exception("drawing exception"); Returns a rendered string

View exception: when using the editor to run Java exception reporting, the viewing method is: view from bottom to top ~ find error information and error reporting lines

Throw throws

Declaring to throw an exception is the second way to handle exceptions in Java:

  • If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to handle this exception, the method should explicitly declare to throw an exception
  • Indicates that the method will not handle these exceptions, but the caller of the method is responsible for handling them

In the method declaration, use the throws statement to declare the list of exceptions thrown:

  • The exception type after throws can be the exception type generated in the method or its parent class

Example of exception thrown by declaration:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * Exception handling method 2: throws + exception type
 * 
 * 1. "throws + The exception type '' is written at the declaration of the method. Indicates the type of exception that may be thrown when the method is executed.
 *     Once an exception occurs during the execution of the method body, an object of exception class will still be generated at the exception code. After this object meets the throws exception
 *     Type is thrown. Exception code and subsequent code will not be executed!
 *     
 * 2. Experience: try catch finally: the exception is really handled. The throws method only throws the exception to the caller of the method, but does not really handle the exception.  
 * 
 * 3. How to choose whether to use try catch finally or throws in development?
 *   3.1 If the overridden method in the parent class does not handle exceptions in the throw mode, the overridden method of the child class cannot use throws, which means that if
 *       There are exceptions in the methods overridden by subclasses, which must be handled in a try catch finally manner.
 *   3.2 In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We recommend using throws for these methods
 *       In a way. For the executed method a, try catch finally can be considered.
 */
public class ExceptionTest2 {
	
	
	public static void main(String[] args){
		try{
			method2();
		}catch(IOException e){
			e.printStackTrace();
		}
		
//		method3();
	}

	public static void method3(){
		try {
			method2();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
	public static void method2() throws IOException{
		method1();
	}
	
	public static void method1() throws FileNotFoundException,IOException{
		File file = new File("hello1.txt");
		FileInputStream fis = new FileInputStream(file);	
		int data = fis.read();
		while(data != -1){
			System.out.print((char)data);
			data = fis.read();
		}
		fis.close();
		System.out.println("hahaha!");
	}
}

Manually throw an exception: Throw

Java exception class objects are automatically generated and thrown by the system except when exceptions occur during program execution It can also be manually created and thrown as needed

  • First, the exception class object is generated, and then the throw operation is implemented through the throw statement (submitted to the Java runtime environment)
    IOException e = new IOException();
    throw e;
  • The exception that can be thrown must be an instance of Throwable or its subclass
    throw new String("want to throw"); String is not an exception type, so it is not true!

User defined exception:

In program development, in order to find the exception problem more accurately, we usually customize the exception class

  • Convenient for developers to quickly find the cause of the problem

Custom exception class:

  • Generally, user-defined exception classes are subclasses of RuntimeException
  • Custom exception classes usually require writing several overloaded constructors.
  • Custom exception requires serialVersionUID serialization unique ID
    Between networks, different projects need to use the same object. You can know the matching object according to this serialization ID, which is equivalent to an ID card!
  • The most important part of a user-defined exception is the name of the exception class. When an exception occurs, you can judge the exception type according to the name

Exception demo case:

MyException
The Java class icon in the IDEA is a lightning bolt. Note: This is a subclass of the Exception class

package com.wsm.dly;

/**
 * How to customize exception classes?
 *      1. Inherited from the existing Exception structure: RuntimeException is an Exception that must not be handled at runtime and Exception must be handled at compile time!
 *      2. Provide global constant: serialVersionUID
 *      3. Provides overloaded constructors
 */

//The Java class icon in the IDEA is a lightning bolt. Note: This is a subclass of the Exception class
public class MyException extends Exception{
    //Serialize unique ID
    private static final long serialVersionUID = -7034897193246939L; 	//Unique serial number, indicating the unique identification of this class!

    //No parameter structure!
    public MyException(){
    }

    //Parameter structure!
    public MyException(String msg){
        //Assign value to the exception information of the parent class!
        super(msg);
    }
}

StudentTest.java

package com.wsm.dly;

public class StudentTest {

    public static void main(String[] args) {
        try {
            Student s = new Student();
            s.regist(-1001);
            System.out.println(s);
        } catch (Exception e) {
            //Print stack and exception information!
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

//Student class
class Student{

    private int id;
    //If it is judged to be negative, an exception will be thrown manually!
    public void regist(int id) throws Exception {   //Throws throws throws an exception to the caller!
        if(id > 0){
            this.id = id;
        }else{
//			System.out.println("the data you entered is illegal!");
            //Manually throw exception object
//			throw new RuntimeException("the data you entered is illegal!");
//			throw new Exception("the data you entered is illegal!");
            throw new MyException("You cannot enter a negative number");

            //FALSE
//			throw new String("negative number cannot be entered")// Throw must throw an exception class or subclass
        }
    }
    @Override
    public String toString() {
        return "Student [id=" + id + "]";
    }
}

Summary:

A custom Exception class is a normal Java class that inherits Exception. It will be marked as an Exception in the IDEA ⚡

  • For the convenience of programmers, declaring exceptions can quickly identify what exceptions can be handled with custom exceptions!
  • ...

Keywords: Java Exception

Added by jmut on Wed, 15 Dec 2021 19:32:08 +0200