Exception handling mechanism

1. Overview of exceptions

An exception is an abnormal condition in the program
Exception architecture: in Java, all exception types are subclasses of the built-in java.lang.Throwable class, that is, Throwable is at the top level of the exception class hierarchy. Under the Throwable class, there are two exception branches, exception and Error. The exception class is used for possible exceptions in the user program. It is also a class used to create a custom exception type class. The exception of Error type is usually a catastrophic fatal Error, which can not be controlled by the program. As shown in Figure 1.

The Exception class Exception is divided into run-time Exception and compile time Exception. Except for run-time Exception, others are called non run-time Exception, also known as Unchecked Exception and Checked Exception.

Exceptions of type Exception include (and their differences):

  • Runtime exceptions are RuntimeException class and its subclasses, such as NullPointerException, IndexOutOfBoundsException, etc. these exceptions are not checked, and the program can choose to capture and handle them or not. These exceptions are generally caused by program logic errors. The program should avoid such exceptions as much as possible from a logical point of view.
  • Compile time exceptions refer to exceptions other than RuntimeException, which belong to Exception class and its subclasses. From the perspective of program syntax, it is an Exception that must be handled. If it is not handled, the program cannot be compiled. Such as IOException, ClassNotFoundException, etc., and user-defined Exception exceptions (generally, the user-defined check Exception is not allowed).

2. Exception handling method

  • try-catch
  • throws
    (1)try-catch

try{
Codes with possible exceptions;
}catch (exception class name variable name){
Exception handling code;
}

After the statement in catch is executed, the program can continue to execute

public class Throwable {
    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]); //ArrayIndexOutOfBoundsException
       }catch (ArrayIndexOutOfBoundsException e){
        //   System.out.println("the index you entered does not exist");
         e.printStackTrace();
          // System.out.println(e.getMessage());
           //System.out.println(e.toString());
       }
    }
}
 try {//try monitoring area
            System.out.println(a/b);
       }catch (Error e) {// Catch (the type of exception you want to catch) catches the exception System.out.println("Error");
       }finally {//Usually deal with the aftermath
           System.out.println("finally");
      }

(2)throws

public void method () throws exception class name{
}

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

The difference between throw and throws:

  • Throw: used in the method body, followed by the exception object name; handled by the statement in the method body; some exception must be thrown when throw is executed
  • throws: used after the method declaration, followed by the exception class name; handled by the caller of the method; indicates a possibility of exceptions, which may not necessarily occur

3. Custom exception

Using Java's built-in Exception class can describe most exceptions during programming. In addition, users can also customize exceptions. Users can customize Exception classes by inheriting Exception class.
It can be divided into the following steps:

  1. Create a custom exception class.
  2. Throw an exception object through the throw keyword in the method.
  3. If the exception is handled in the method that currently throws the exception, you can use the try catch statement to catch and handle it; otherwise, indicate the exception to be thrown to the method caller through the throws keyword in the method declaration, and continue to the next step.
  4. Catch and handle exceptions in the caller of the exception method.
public class Teacher {
    public void checkScore(int score) throws ScoreException {
        if(score < 0 || score >100){
            throw new ScoreException("The score you gave is wrong. The score should be 0-100 between");
        }else{
            System.out.println("The score is normal");
        }
    }
}
import java.util.Scanner;

public class ScoreDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a score:");
        int s = sc.nextInt();
       Teacher t = new Teacher();
        try {
            t.checkScore(s);
        } catch (ScoreException e) {
            e.printStackTrace();
        }
    }
}

Tags: Java Algorithm

Posted on Wed, 24 Nov 2021 11:45:47 -0500 by formxshape