java exception description

1. Abnormal

1.1 abnormality (memory)

  • Overview of exceptions

    An exception is an abnormal condition in the program

  • Abnormal architecture

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-EuvFnCDO-1641957293904)(img(_ exception architecture. png)]

1.2 difference between compile time exception and run-time exception (memory)

  • Compile time exception

    • Are all Exception classes and their subclasses
    • The processing must be displayed, otherwise the program will have an error and cannot be compiled
  • Runtime exception

    • Are RuntimeException class and its subclasses
    • You do not need to display the handling, but you can also handle the exception as you do at compile time
  • Illustration

    [the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wYmq5IlX-1641957293905)(img__ compile time exception and run-time exception. png)]

1.3 JVM default exception handling method (understood)

  • 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:
    • The name of the exception, the cause of the error and the location of the exception are output to the console
    • Program stop

1.4 viewing abnormal information (understanding)

When the console prints the exception information, it will print the exception class name, the reason for the exception and the location of the exception

When debugging a bug, we can find the location of the exception, analyze the cause, and modify the exception code according to the prompt

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-F5wQY0g2-1641957293906)(img_ view exception information. png)]

1.5 handling exceptions in throws mode (application)

  • Define format

    public void method() throws Exception class name {
        
    }
    
  • Sample code

    public class ExceptionDemo {
        public static void main(String[] args) throws ParseException{
            System.out.println("start");
    //        method();
              method2();
    
            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]);
        }
    }
    
  • matters needing attention

    • 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 throws is adopted, the display declaration is made on the method. Whoever calls this method in the future will handle it
    • Because runtime exceptions occur only at runtime, you can not write after the method. Exceptions at runtime are handled by the jvm by default

1.6 throw exception (application)

  • format

    throw new exception();

  • be careful

    This format is in the method, which means that the current code throws an exception manually, and the following code does not need to be executed

  • The difference between throws and throw

    throwsthrow
    Used after the method declaration, followed by the exception class nameUsed in the method body, followed by the exception object name
    Indicates a declared exception, which may occur when calling this methodIndicates that the exception object is thrown manually, which is handled by the statement in the method body
  • Sample code

    public class ExceptionDemo8 {
        public static void main(String[] args) {
            //int [] arr = {1,2,3,4,5};
            int [] arr = null;
            printArr(arr);//Will receive an exception
                            //We also need to handle exceptions ourselves
        }
    
        private static void printArr(int[] arr) {
            if(arr == null){
                //Does the caller know that the print was successful?
                //System.out.println("parameter cannot be null");
                throw new NullPointerException(); //When the parameter is null
                                                //An exception object is created manually and thrown to the caller, resulting in an exception
            }else{
                for (int i = 0; i < arr.length; i++) {
                    System.out.println(arr[i]);
                }
            }
        }
    
    }
    

1.7 try catch exception handling (application)

  • Define format

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

    • The program starts from the code in try
    • If an exception occurs, it will jump to the corresponding catch for execution
    • After execution, the program can continue to execute
  • 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");
            }
        }
    }
    
  • be careful

    1. If there is no problem in the try, how to execute it?

      All the code in try will be executed, and the code in catch will not be executed

    2. If there is a problem in try, will the code below try be executed?

      Then jump directly to the corresponding catch statement, and the code under try will not be executed again
      When all the statements in catch are executed, it means that the whole system is fully executed, and continue to execute the following code

    3. If the problem is not captured, how does the program run?

      Then try... catch is equivalent to not writing Then I didn't deal with it myself
      By default, it is handed over to the virtual machine

    4. How to deal with multiple exceptions that may occur at the same time?

      If there are multiple exceptions, you can write multiple catch es
      Note: if there is a child parent relationship between multiple exceptions Then the parent class must be written below

1.8 Throwable member method (application)

  • common method

    Method nameexplain
    public String getMessage()Returns the detailed message string for this throwable
    public String toString()Returns a short description of this throw
    public void printStackTrace()Output the abnormal error message to the console
  • Sample code

    public class ExceptionDemo02 {
        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]); //new ArrayIndexOutOfBoundsException();
                System.out.println("Is it accessible here");
            } catch (ArrayIndexOutOfBoundsException e) { //new ArrayIndexOutOfBoundsException();
    //            e.printStackTrace();
    
                //public String getMessage(): returns the detailed message string of this throwable
    //            System.out.println(e.getMessage());
                //Index 3 out of bounds for length 3
    
                //public String toString(): returns a short description of this throw
    //            System.out.println(e.toString());
                //java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    
                //public void printStackTrace(): output the abnormal error information on the console
                e.printStackTrace();
    //            java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    //            at com.itheima_02.ExceptionDemo02.method(ExceptionDemo02.java:18)
    //            at com.itheima_02.ExceptionDemo02.main(ExceptionDemo02.java:11)
    
            }
        }
    }
    

1.9 abnormal practice (application)

  • demand

    Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old. If it exceeds this range, it is abnormal data and cannot be assigned It needs to be re entered until it is correct

  • Implementation steps

    1. Create student object
    2. Enter the name and age on the keyboard and assign it to the student object
    3. If it is illegal, enter the data again
  • code implementation

    Student class

    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age >= 18 && age <= 25){
                this.age = age;
            }else{
                //When the age is illegal, an exception occurs
                throw new RuntimeException("Age out of range");
            }
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    Test class

    public class ExceptionDemo12 {
        public static void main(String[] args) {
            // Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old,
            // Beyond this range is abnormal data and cannot be assigned It needs to be re entered until it is correct.
    
            Student s = new Student();
    
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter your name");
            String name = sc.nextLine();
            s.setName(name);
           while(true){
               System.out.println("Please enter age");
               String ageStr = sc.nextLine();
               try {
                   int age = Integer.parseInt(ageStr);
                   s.setAge(age);
                   break;
               } catch (NumberFormatException e) {
                   System.out.println("Please enter an integer");
                   continue;
               } catch (AgeOutOfBoundsException e) {
                   System.out.println(e.toString());
                   System.out.println("Please enter an age that matches the range");
                   continue;
               }
               /*if(age >= 18 && age <=25){
                   s.setAge(age);
                   break;
               }else{
                   System.out.println("Please enter the age that meets the requirements ");
                   continue;
               }*/
           }
            System.out.println(s);
    
        }
    }
    

1.10 custom exception (application)

  • Overview of custom exceptions

    When the exceptions provided in Java can not meet our needs, we can customize the exceptions

  • Implementation steps

    1. Define exception class
    2. Write inheritance
    3. Provide null parameter construction
    4. Provide structure with parameters
  • code implementation

    Exception class

    public class AgeOutOfBoundsException extends RuntimeException {
        public AgeOutOfBoundsException() {
        }
    
        public AgeOutOfBoundsException(String message) {
            super(message);
        }
    }
    

    Student class

    public class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age >= 18 && age <= 25){
                this.age = age;
            }else{
                //If the exceptions provided in Java can not meet our needs, we can use custom exceptions
                throw new AgeOutOfBoundsException("Age out of range");
            }
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    

    Test class

    public class ExceptionDemo12 {
        public static void main(String[] args) {
            // Enter the student's name and age on the keyboard, of which the age is 18 - 25 years old,
            // Beyond this range is abnormal data and cannot be assigned It needs to be re entered until it is correct.
    
            Student s = new Student();
    
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter your name");
            String name = sc.nextLine();
            s.setName(name);
           while(true){
               System.out.println("Please enter age");
               String ageStr = sc.nextLine();
               try {
                   int age = Integer.parseInt(ageStr);
                   s.setAge(age);
                   break;
               } catch (NumberFormatException e) {
                   System.out.println("Please enter an integer");
                   continue;
               } catch (AgeOutOfBoundsException e) {
                   System.out.println(e.toString());
                   System.out.println("Please enter an age that matches the range");
                   continue;
               }
               /*if(age >= 18 && age <=25){
                   s.setAge(age);
                   break;
               }else{
                   System.out.println("Please enter the age that meets the requirements ");
                   continue;
               }*/
           }
            System.out.println(s);
    
        }
    }
    

Keywords: Java Back-end

Added by AoA_Falcon on Wed, 12 Jan 2022 05:26:30 +0200