Exception handling in Java

Exception handling in Java

Definition of exception

Exception: in the Java language, abnormal conditions in program execution are called "exceptions". Syntax errors and logic errors in the development process are not exceptions.

1. Abnormal architecture

The abnormal events that occur during the execution of Java programs can be divided into two categories:

  1. Error: a serious problem that cannot be solved by Java virtual machine. Generally, targeted code is not written for processing. Such as: JVM system internal error, resource exhaustion and other serious situations. For example:
    • Stack overflow: = = StackOverflowError==
    • Heap overflow = = outofmemoryerror, OOM = =;
  2. Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example:
    • Null pointer access: NullPointerException
    • An attempt was made to read a file that does not exist: = = FileNotFoundException==
    • Loss of network connection:
    • Array subscript out of bounds: ArrayIndexOutOfBoundsException
Abnormal architecture
 * java.lang.Throwable
 * 		|-----java.lang.Error:Generally, targeted code is not written for processing.
 * 		|-----java.lang.Exception:Exceptions can be handled
 * 			|------Compile time exception(checked)Bytecode files will not be generated
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 			|------Runtime exception(unchecked,RuntimeException)
 * 					|-----NullPointerException  //Null pointer exception
 * 					|-----ArrayIndexOutOfBoundsException//Array subscript out of bounds
 * 					|-----ClassCastException    //Type conversion exception
 * 					|-----NumberFormatException //Abnormal encoding format
 * 					|-----InputMismatchException//Input mismatch
 * 					|-----ArithmeticException   //Arithmetic anomaly

Inheritance of exception classes in java

2. It can be divided into two categories according to the time when the abnormality occurs

  1. ==Compile time exception = =: execute javac Possible exceptions during exe naming; An exception that the compiler does not require forced handling. Generally refers to the logic error in programming, which is an exception that programmers should actively avoid. java.lang.Runtime Exception class and its subclasses are all runtime exceptions. This kind of exception can not be handled, because this kind of exception is very common. If it is fully handled, it may affect the readability and running efficiency of the program
  2. Runtime exception: execute Java When naming exe, the exception that occurs refers to the 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 such exceptions, if the program does not handle them, they may bring unexpected results.

3. Common exception types

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;

/**
 * FileName: ExceptionTest
 * Description: Abnormal test
 *
 * @author Reanon
 * @create: 2020/12/16 21:08
 */

public class ExceptionTest {
    // ******************The following are runtime exceptions***************************
    // ArithmeticException
    @Test
    public void test6() {
        int a = 10;
        int b = 0;
        System.out.println(a / b);
    }

    // InputMismatchException
    @Test
    public void test5() {
        // input handle 
        Scanner scanner = new Scanner(System.in);
        int score = scanner.nextInt();
        System.out.println(score);
        scanner.close();
    }

    // NumberFormatException
    @Test
    public void test4() {

        String str = "123";
        str = "abc";
        int num = Integer.parseInt(str);
    }

    // ClassCastException
    @Test
    public void test3() {
        Object obj = new Date();
        String str = (String) obj;
    }

    // IndexOutOfBoundsException
    @Test
    public void test2() {
        // ArrayIndexOutOfBoundsException
		int[] arr = new int[10];
		System.out.println(arr[10]);

		// StringIndexOutOfBoundsException
        String str = "abc";
        System.out.println(str.charAt(3));
    }

    // NullPointerException
    @Test
    public void test1() {
		int[] arr = null;
		System.out.println(arr[3]);

        String str = "abc";
        str = null;
        System.out.println(str.charAt(0));

    }

    //******************The following are compile time exceptions***************************
    // FileNotFoundException must be captured
    @Test
    public void test7() throws IOException {
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);

        int data = fis.read();
        while (data != -1) {
            System.out.print((char) data);
            data = fis.read();
        }
		// Close file
        fis.close();
    }
}

Exception handling

1. Grasping and throwing model of java exception handling

Process 1: "throwing"

  • During the normal execution of the program, once an exception occurs, 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 exception objects:

  1. Exception object automatically generated by the system
  2. Manually generate an exception object and throw it

Process 2: "grasping": it can be understood as the exception handling method:

  1. Capture and process: = = try catch finally==
  2. Throw to the upper layer: = = throws==

2. Method 1: try catch finally

2.1 grammar

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 be executed
}

explain:

  1. ==finally = = is optional.

  2. try is used to wrap the possible exception code. In the process of execution, once an exception occurs, 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 will enter the catch for exception processing. Once the processing is completed, it will jump out of the current try catch structure (if finally is not written, continue to execute the subsequent code)

  4. If the exception type in catch has no child parent relationship, it doesn't matter who declares it on the top and who declares it on the bottom. 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. The variables declared in the try structure cannot be called after the try structure.

  7. Try catch finally structures can be nested

How to treat compile time exceptions and run-time exceptions in code?

  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 runtime.
  2. In development, because 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 = =.
import org.junit.Test;

/**
 * FileName: TryCatchTest
 * Description:
 *
 * @author Reanon
 * @create: 2020/12/16 21:21
 */

public class TryCatchTest {
    @Test
    public void test() {
        String str = "123";
        str = "abc";
        try {
            int num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            // printStackTrace(), print stack information
            e.printStackTrace();
            // String getMessage(), output error message
            System.out.println(e.getMessage());

            System.out.println("Exception in numeric conversion");
        }
    }
}

2.2. finally:

  1. finally is optional.
  2. finally, what is declared is the code that must be executed. Even if there are exceptions in catch, return statements in try, return statements in catch, etc.
  3. Resources such as database connection, input / output stream and network programming Socket cannot be recycled automatically by JVM. We need to release resources manually. When = = resource is released, it needs to be declared in finally = =.
import org.junit.Test;

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

/**
 * FileName: FinallyTest
 * Description:
 *
 * @author Reanon
 * @create: 2020/12/16 21:35
 */

public class FinallyTest {

    @Test
    public void test1() {
        File file = new File("hello.txt");
        // Define a file stream first
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
			// File input stream
            int data = fis.read();
            while (data != -1) {
                System.out.print((char) data);
                data = fis.read();
            }
        } catch (FileNotFoundException e) {
            // No file exception
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // If the file is open
                if (file != null) {
                    // Close file stream
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3. Mode 2: throws

"Throws + exception type" = = written at the declaration of the method = =. Indicates the type of exception that may be thrown when this 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. When this object meets the exception type after throws, it will be thrown. Exception code and subsequent code will not be executed!

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * FileName: ThrowsTest
 * Description:
 *
 * @author Reanon
 * @create: 2020/12/16 21:57
 */

public class ThrowsTest {
    public static void main(String[] args) {
        // Catch exception 
        try {
            method2();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void method2() throws IOException {
        method1();
    }
	
    public static void method1() throws IOException { // Throw an exception directly
        File file = new File("hello.txt");
        FileInputStream fis = new FileInputStream(file);

        int data = fis.read();
        while (data != -1) {
            System.out.print((char) data);
            data = fis.read();
        }

        fis.close();
    }
}

4. Compare the two treatment methods

  • Try catch finally: the exception is really handled.
  • Throws simply throws the exception to the caller of the method== Did not really handle the exception = =.

5. How to choose two processing methods in development?

  • 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 overridden method of the child class, it must be handled in the try catch finally mode.
  • In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We suggest that these methods be handled in the way of throws. For the executed method a, try catch finally can be considered.

>Supplement > > one of the rules of method Rewriting: the exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the method overridden by the parent class

Manually throw exception object

1. Instructions for use

During program execution, in addition to automatically throwing exception objects, we can also manually throw exception class objects.

2. Classic interview questions

Difference between throw and throws:

  • throw: refers to the process of throwing an object of an exception class and generating an exception object; Declaration in method body.
  • throws: a method of exception handling, which is declared at the declaration of the method.

3. Code example

/**
 * FileName: StudentTest
 * Description:
 *
 * @author Reanon
 * @create: 2020/12/16 22:11
 */

public class StudentTest {
    public static void main(String[] args) {
        Student s = new Student();
        s.regist(-1001);
        System.out.println(s);
    }

}

class Student {
    private int id;

    public void regist(int id) {
        if (id > 0) {
            this.id = id;
        } else {
            // 1. Manually throw the Runtime exception object without processing
            throw new RuntimeException("The data you entered is illegal!");
            
            try {
                // 2. If an exception object is generated, it must be handled manually
                throw new Exception("The data you entered is illegal!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 3. Use custom exception
            try {
                throw new MyException("You cannot enter a negative number");
            } catch (MyException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public String toString() {
        return "Student [id=" + id + "]";
    }
}

Custom exception class

1. How to customize exception classes

  1. Inherited Exception structures: RuntimeException, Exception
  2. Provide global constant: serialVersionUID (unique identification of the class)
  3. Provides overloaded constructors

2. Code example

// 1. Inherit the existing Exception class Exception
public class MyException extends Exception{
	// 2. Provide global constant serial number
	static final long serialVersionUID = -7034897193246939L;
	
    // 3. Provide overloaded constructor
	public MyException(){
	}
    // This is necessary
	public MyException(String msg){
		super(msg);
	}
}

summary

Comprehensive practice

Case 1: writing the application ecmdef Java, which receives two parameters from the command line. It is required that negative numbers cannot be entered and the division of two numbers is calculated. yes

  • Inconsistent data type: NumberFormatException
  • Missing command line parameter: arraylndexofboundsexception
  • Except 0: ArithmeticException
  • Enter a negative number: EcDef (custom exception) for exception handling.

Tips:

  1. Define the exception method (ecm) in the main class (EcmDef) to divide two numbers.

  2. Use exception handling statements in the main() method for exception handling.

  3. In the program, customize the exception class (EcDef) corresponding to the input negative number.

  4. Accept parameters at runtime

    java EcmDef 20 10 // args[0]="20" args[1]="10"
    
  5. The static method parseInt(String s) of the Interger class converts s into the corresponding int value.

    • For example: int a = interger parselnt("314");
/**
 * FileName: EcmDef
 * Description: Write the application ecmdef Java, which receives two parameters from the command line. It is required that negative numbers cannot be entered and the division of two numbers is calculated.
 *
 * @author Reanon
 * @create: 2020/12/16 22:34
 */

public class EcmDef {
    public static void main(String[] args) {
        try {
            int i = Integer.parseInt(args[0]);
            int j = Integer.parseInt(args[1]);
            ecm(i, j);
        } catch (NumberFormatException e) {
            System.out.println("Inconsistent data type");
        } catch (ArithmeticException e) {
            System.out.println("Divide by 0");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Missing command line argument");
        } catch (EcDef e) {
            // Print error message
            System.out.println(e.getMessage());
        }
    }

    public static int ecm(int i, int j) throws EcDef {
        if (i < 0 || j < 0) {
            // When a negative number is entered
            // Throw custom exception EcDef
            throw new EcDef("Enter a negative number");
        }
        return i / j;
    }
}

// Custom exception.
// 1. Inherit the existing Exception class Exception
class EcDef extends Exception {
    // 2. Provide global constant serial number
    static final long serialVersionUID = -338751699324229948L;
	
    // 3. Heavy load constructor
    public EcDef() {}

    public EcDef(String msg) {
        super(msg);
    }
}

Reference link

Tags: Java Interview Junit gitee imgs

Posted by nadeemshafi9 on Thu, 31 Mar 2022 09:59:50 +1030