Take you to understand the exception handling mechanism in Java

Take you to understand the exception handling mechanism in Java


Exception handling

1 Introduction

If a user loses user data due to a program error or some external environmental influences during the running of the program, the user may no longer use the program. In order to avoid such things from happening, at least the following points should be done :

  • Notify users of errors
  • Save all work results
  • Allow users to exit the program in a proper manner

So, Java uses a technique called exception handling error trapping mechanism of the process. The most fundamental advantage of exception handling is to separate detection errors (completed by the called method) from handling errors (completed by the calling method).

2. Exception type

Abnormality: In the Java language, abnormal situations that occur during program execution are called "abnormalities". (Syntax errors and logic errors in the development process are not abnormal) 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: internal errors of the JVM system, resource exhaustion and other serious situations. For example: StackOverflowError and OOM. Generally do not write targeted code for processing.
  • Exception: Other general problems caused by programming errors or accidental external factors can be handled with targeted codes. As can be seen from the above figure, Exception is broken down into two branches
  • RuntimeException(Exception during runtime):
    • NullPointerException Null pointer exception
    • ArrayIndexOutOfBoundsException Array corner mark out of bounds
    • ClassCastException Type conversion exception
    • NumberFormatException Number format is abnormal
    • InputMismatchException Input type is abnormal
    • ArithmeticException Arithmetic operation abnormal
    • and many more
  • IOException
  • ClassNotFoundException
  • More classes

From the program execution process, it is divided into

  1. Runtime exception
  • Refers to exceptions that the compiler does not require mandatory handling. Generally refers to logic errors during programming, which are exceptions that programmers should actively avoid. The java.lang.RuntimeException class and its subclasses are runtime exceptions.
  • For this type of exception, you can directly find the code that has the problem without processing it, and evade it. Because this kind of exception is very common, it may affect the readability and operating efficiency of the program if it is fully processed.
  1. Compile time exception
  • Refers to the exception that must be handled by the compiler. That is, the general abnormality 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 bad results.

Compile-time exception: An exception that may occur when naming javac.exe is executed. Runtime exceptions: exceptions that occur when naming java.exe is executed.

RuntimeException, Error and their subclasses are called unchecked exceptions. All other exceptions are called checked exceptions, which means that the compiler will force the programmer to check and handle them through a try catch block, or declare them in the method header.

3. Detailed operation of exception handling

Java's exception handling model is based on three operations:

  • Declaring an exception
  • Throwing an exception
  • Catch an exception

3.1 Declare an exception

In Java, the currently executed statement must belong to a method. The Java interpreter calls the main method to start executing a program. Each method must declare the type of the == must check exception == it may throw. This is called a declaring exception.

In order to declare an exception in a method, the keyword throws is used in the method header :

public void myMethod  throws Exception1 Exception2

Tips: If the method does not declare an exception in the parent class, then it cannot be inherited in the subclass to declare the exception.

3.2 Throw an exception

A program that detects an error can create an instance of the appropriate exception type and throw it . This is called throwing an exception. Once the object is thrown, the following code is no longer executed.

IllegalArgumentException ex =new IllegalArgumentException("Wrong Argument");
throw ex;
throw new 111egalArgumentException("Wrong Argument");

Generally, each exception class in JavaAPI has at least two construction methods: a no-argument construction method and a construction method with a String parameter that can describe the exception . This parameter is called exception message (exceptionmessage), it can be obtained with getMessage().

3.3 Catch exceptions and finally clause

You can start with the current method and follow the method call chain to find this handler in the reverse direction of the exception. Check the catch blocks one by one from the first to the last to determine whether the exception class instance in the catch block is the type of the exception object. If it is, the exception object is given to the declared variable, and then the code in the catch block is executed. If no exception handler is found, Java will exit this method, pass the exception to the method that called this method, and continue the same process to find the handler. If no processor is found in the method chain called, the program will terminate and an error message will be printed on the console. The process of finding a processor is called catching an exception. When an exception is thrown, it can be caught and handled in a try-catch block.

...... //
catch( ExceptionName1 e ){
...... //ExceptionName1 
catch( ExceptionName2 e ){
...... //ExceptionName2 
} finally{
...... //
  • The first step in try to catch an exception is to use the try{...} statement block to select the scope of the exception, and place the code that may be abnormal in the try block.
  • catch (Exceptiontype e)
    • In the catch statement block is the code for processing the exception object. Each try statement block can be accompanied by one or more catch statements to handle the different types of exception objects that may be generated
    • Various exception classes can be derived from a common parent class. If a catch block can capture the exception objects of a parent class, it can capture the exception objects of all subclasses of that parent class.
    • If the exception type in catch has no child-parent relationship, it doesn't matter who declares on the top and who declares on the bottom.
    • If the exception type in catch satisfies the relationship between the child and the parent class, the child class must be declared above the parent class . Otherwise, report an error
  • finally
    • The final step in catching an exception is to provide a unified exit for exception handling through the finally statement, so that the state of the program can be managed uniformly before the control flow is transferred to other parts of the program.
    • Regardless of whether an abnormal event occurs in the try code block, whether the catch statement is executed, whether the catch statement is abnormal, whether there is a return in the catch statement, the statements in the finally block will be executed.
  • finally statement and catch statement are optional

3.4 Obtaining information from the exception

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

  • String getMessage() Get exception information, return string
  • void printStackTrace() Get the exception class name and exception information, as well as the location of the exception in the program. The return value is void.
  • String toString(): If it exists, return a formatted string containing class name, method name, file name and line number.
  • getStackTrace :StackTraceElement[] Returns an array of stack trace elements representing the stack trace associated with the exception object

4. Create a custom exception class

If you get into a problem that cannot be properly described by a predefined exception class, you can derive the Exception class or its subclasses.

  • Generally, user-defined exception classes are inherited from the existing exception structure: RuntimeException and Exception.
  • Custom exception classes usually need to write several overloaded constructors.
  • Custom exceptions need to provide serialVersionUID
  • Custom exceptions are thrown through throw.
  • The most important thing for custom exceptions is the name of the exception class. When an exception occurs, the exception type can be judged based on the name

For example, the following code:

public class MyException extends Exception {
    static final long serialVersionUID = 13465653435L;
    private int idnumber;

    public MyException(String message, int id) {
        this.idnumber = id;
    public int getId() {
        return idnumber;

public class MyExpTest {
    public void regist(int num) throws MyException {
        if (num < 0) {
            throw new MyException(" ", 3);
        } else {
            System.out.println(" " + num);

    public void manager() {
        try {
        } catch (MyException e) {
            System.out.print(" " + e.getId());
        System.out.print("   ");

    public static void main(String[] args) {
        MyExpTest t = new MyExpTest();

Output result: