java exception overview


1, What is an exception

2, Exception architecture

3, Exception handling mechanism

4, Custom exception

1, What is an exception

  • In actual work, the situation encountered can not be very perfect. For example, for a module you write, the user input does not necessarily meet your requirements, your program wants to open a file, the file may not exist or the file format is wrong, you want to read the data in the database, the data may be empty, etc. If our program runs again, the memory or hard disk may be full. wait.

  • During the operation of the software program, it is very likely to encounter these abnormal problems just mentioned. We call them exceptions, which means exceptions. These, exceptions, or exceptions, how can we make our program deal with them reasonably. Without the F program crashing.

  • Exceptions refer to unexpected conditions during program operation, such as file missing, network connection failure, illegal parameters, etc.

  • The exception occurs during the program running, which affects the normal program execution process.

Simple classification

To understand how Java exception handling works, you need to master the following three types of exceptions:

  • Checking exception: the most representative checking exception is the exception caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a nonexistent file, an exception occurs. These exceptions cannot be simply ignored at compile time.

  • Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time.

  • Error: an error is not an exception, but a problem out of the programmer's control. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

2, Exception architecture

  • Java treats exceptions as objects and defines a base class java.lang.Throwable as the superclass of all exceptions.

  • Many Exception classes have been defined in the Java API. These Exception classes are divided into two categories: Error and Exception.


  • The Error class object is generated and thrown by the Java virtual machine. Most errors have nothing to do with the operation performed by the coder.

  • Java virtual machine running error. OutOfMemoryError will appear when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java virtual machine (JVM)   Thread termination is generally selected;

  • In addition, when the virtual machine attempts to execute the application, such as class definition error (NoClassDefFoundError) and link error (LinkageError). These errors are not traceable because they are outside the control and processing power of the application, and most of them are not allowed when the program is running.


There is an important subclass RuntimeException (runtime Exception) in the Exception branch

  • ArrayIndexOutOfBoundsException (array subscript out of bounds)

  • NullPointerException (null pointer exception)

  • ArithmeticException (arithmetic exception)

  • MissingResourceException (missing resource)

  • ClassNotFoundException (class not found) and other exceptions. These exceptions are not checked. The program can choose to capture and handle them or not.

◆ these exceptions are generally caused by program logic errors, and the program should avoid such exceptions as far as possible from the perspective of logic;

◆ difference between Error and Exception: Error is usually a catastrophic and fatal Error, which cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM)   Generally, you will choose to terminate the thread; Exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program.

3, Exception handling mechanism

  • Throw exception

  • Catch exception

  • There are five keywords for exception handling: try, catch, finally. throw and throws

Capture demo

package com.alic.excption;

public class Test {

    public static void main(String[] args) {

        int a=1;

        int b=0;

        //If multiple exceptions are caught, they are caught from small to large

        try { //try monitoring area

            System. out. println(a/b);

        }catch (Error e){ //Catch (type of exception you want to catch!) catch exception

            System. out. println("Error");

        }catch (Exception e){

            System. out. println("Exception");

        }catch (Throwable t){

            System. out . println("Throwable" );

        } finally { //Deal with the aftermath

            System. out. println("finally");//Finally, don't finally. Suppose I0, resource, close!



    public void a(){



    public void b(){




Throw exception

package com.alic.excption;

public class Test {

    public static void main(String[] args) {

        new Test().test(1, 0);


    //Actively throw exception

    public void test(int a, int b) throws ArithmeticException{

        if (b == 0) { //throw throw

            throw new ArithmeticException(); // Actively throw an exception





[note] if the method throws an exception, the program will terminate when there is an exception, and the subsequent code will not handle it

4, Custom exception

Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can customize exceptions. You can customize the Exception class by inheriting the Exception class.

Using custom exception classes in programs can be roughly divided into the following steps:

  1. Create a custom exception class.

  1. Throw an exception object through the throw keyword in the method.

  2. If an exception is handled in the method that currently throws an exception, you can use the try catch statement to catch and handle it; Otherwise, use the throws keyword at the method declaration to indicate the exception to be thrown to the method caller, and continue with the next operation.

  3. Catch and handle exceptions in the caller of the exception method.

Custom exception

package com.alic.exception.demo01;

public class MyException extends Exception{


    public String toString() {

        return "MyException{Throw exception}";




package com.alic.exception.demo01

public class Test {

    public static void main(String[] args) {

        try { //Abnormal monitoring


        } catch (MyException e) {//Catch exception




    //Define the test method and throw a user-defined exception

    public static void test(int num) throws MyException {

        if(num == 0){

            throw new MyException();




Experience summary in practical application

  • When handling runtime exceptions, logic is used to reasonably avoid and assist in try catch processing

  • After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed

  • For uncertain code, you can also add try catch to handle potential exceptions

  • Try to handle exceptions, and never simply call printStackTrace() to print out

  • How to handle exceptions should be determined according to different business requirements and exception types

  • Try to add finally statement blocks to release the occupied resources


Tags: Java Spring JavaSE

Posted by DeGauss on Mon, 20 Sep 2021 19:11:18 +0530