Simple summary of Java exception system

Keywords: Java Exception

catalogue

preface

1, Exception overview

2, Exception handling

3, Custom exception


preface

    hello, guys, long time no see! In today's article, I want to talk about the exception class of Java. I believe the little friends who have learned Java are not unfamiliar with exceptions. Then the little friends who have learned can simply have a look and review it; If you haven't learned or are learning, you can take a serious look, which may inspire and help you. (*^▽^*)

1, Exception overview

1. What is an exception?

    An exception refers to an abnormal condition in the program. For example, ArrayIndexOutOfBoundsException (array index out of bounds exception: the specified index value exceeds the array len gt h < hee hee hee, many little friends who have just started learning Java have encountered this problem?), ClassCastException (cast exception: the code attempts to convert an object to an instance that does not belong to it. For example, this exception will be reported if you cast a cat object to a dog object).

2. Abnormal architecture

    Error: a serious problem that does not need to be handled
    Exception: called an exception class, it represents a problem that the program itself can handle

  • RuntimeException: it is not checked during compilation. After a problem occurs, we need to come back and modify the code
  • Non RuntimeException: it must be handled during compilation. Otherwise, the program cannot be compiled and cannot run normally

3. The difference between compile time exception and runtime exception

    Exceptions in Java are divided into two categories: compile time exceptions and run-time exceptions, also known as checked exceptions and non checked exceptions.
    All RuntimeException classes and their subclasses are called runtime exceptions, and other exceptions are compile time exceptions.

  • Compile time exception: the processing must be displayed (that is, it must be handled manually. Refer to the following for the processing scheme), otherwise the program will have an error and cannot be compiled.
  • Run time exception: there is no need to display the handling, and it can also be handled as the compile time exception.


2, Exception handling

1. Default processing scheme of JVM (automatic processing)

    If there is a problem with the program, we do not do any processing. Finally, the JVM will do the default processing. The processing method includes the following two steps:

  1. Output the name, reason, location and other information of the exception on the console.
  2. End the program.  

  Generally, we can ignore runtime exceptions and let the JVM handle them automatically (display processing is also required if you want the program to continue running without termination); however, for compile time exceptions, the JVM's default processing scheme is not feasible, and we must display (manual) processing. Next, I will introduce two display processing schemes: try...catch and throws.

2. try...catch of exception handling

    The biggest advantage of the try...catch display processing scheme is that if an exception occurs, it will not terminate the program. After the exception information is output, the program will continue to run.

  1) Define format

try {
	Possible exception codes;
} catch(Exception class name variable name) {
	Exception handling code;
}

  2) Execution process
    The program starts from the code in try. If an exception occurs, an exception class object will be automatically generated, and the exception class object will be submitted to the Java runtime system. When the Java runtime system receives the exception object, it will find the matching exception class in the catch and handle the exception after finding it. After execution, the program can continue to execute.

  3) Sample code

public class ExceptionDemo01 {
    public static void main(String[] args) {
        System.out.println("start");
        method();
        System.out.println("end");
    }

    public static void method() {
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[3]);
            System.out.println("Is it accessible here");
        } catch (ArrayIndexOutOfBoundsException e) {
//            System.out.println("the array index you accessed does not exist, please go back and modify it to the correct index");
            e.printStackTrace();
        }
    }
}

3. throws of exception handling

    Sometimes when we don't want to use try catch or don't have permission to use try catch to handle exceptions, we can choose the throw method. However, throws is only a temporary way to handle exceptions. Finally, try...catch should be used when calling methods.

  1) Define format

public void method() throws Exception class name {
    
}

  2) Sample code

public class ExceptionDemo {
    public static void main(String[] args) {
        System.out.println("start");
//        method();
        try {
            method2();
        }catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("end");
    }

    //Compile time exception
    public static void method2() throws ParseException {
        String s = "2048-08-09";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(s);
        System.out.println(d);
    }

    //Runtime exception
    public static void method() throws ArrayIndexOutOfBoundsException {
        int[] arr = {1, 2, 3};
        System.out.println(arr[3]);
    }
}

  3) Precautions

  • The throws format follows the parentheses of the method.

  • Exceptions must be handled during compilation. There are two processing schemes: try...catch... Or throws. If the throw scheme is adopted, who will call and who will handle them in the future.

  • Runtime exceptions can not be handled. After a problem occurs, we need to come back and modify the code.

3, Custom exception

1.Throwable common member methods

  Before introducing user-defined exceptions, let's introduce the common member methods of Throwable class, mainly including the following three:  

  • getMessage(): returns the cause of the exception.
  • toString(): returns the name of the exception and the cause of the exception.
  • printStackTrace(): output the name of the exception, the cause of the exception and the exception location information on the console.

2. Custom exception

    Sometimes the Exception class provided by Java may not meet our actual development needs, so we need to customize the Exception class. Custom Exception classes are very simple. We can add our own Exception classes to the Java Exception system by inheriting the Exception class with the extends keyword.

  1) Define format

  

  2) Sample code

>Custom exception class

public class ScoreException extends Exception {

    public ScoreException() {}

    public ScoreException(String message) {
        super(message);
    }

}

>Teacher class

public class Teacher {
    public void checkScore(int score) throws ScoreException {
        if(score<0 || score>100) {
//            throw new ScoreException();
            throw new ScoreException("The score you gave is wrong. The score should be 0-100 between");
        } else {
            System.out.println("Normal performance");
        }
    }
}

>Test class

public class Demo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a score:");

        int score = sc.nextInt();

        Teacher t = new Teacher();
        try {
            t.checkScore(score);
        } catch (ScoreException e) {
            e.printStackTrace();
        }
    }
}

3. Difference between throws and throw

The above custom exception example code has a keyword throw, which throws an exception object. So what's the difference between it and throws? The blogger has sorted it out for you:

ps: it's not easy for bloggers to create. Let's give praise to the friends who like this article!   ღ (´ᴗᴗღ) comparison Center

Posted by pelegk2 on Sat, 20 Nov 2021 20:20:01 -0800