Exception and exception handling

Concept of exception

An exception is an abnormal condition that occurs during the execution of a program, which will eventually lead to an abnormal stop of the JVM.

Anomaly classification


**java.lang.Throwable: * * class is a superclass for all errors or exceptions in the Java language.

  • **Exception: * * compile time exception, which is a problem in compiling (writing code) java programs
    RuntimeException: run-time exception, a problem that occurs during the running of a java program
    The exception is equivalent to a small problem (cold, fever) in the program. Deal with the exception and the program can continue to execute (take some medicine and continue the revolutionary work)
  1. **Error: * * error
    An error is equivalent to an incurable problem (SARS, AIDS) in the program. The source code must be modified before the program can continue to execute

Handling of exceptions and errors

Exception handling

A. Face compilation exception

1. throws

Alt + enter - > select first

Throws throws the exception to the virtual machine for processing. If there is no match, a parsing exception will be thrown to interrupt the processing.

2. try-catch

. Alt + enter - > after selecting the second exception handler, the program can run normally. (after throwing an exception, the subsequent code continues to run)

B. Face the exception at runtime

try
Code with possible exceptions
catch
How to handle exceptions

Error handling

The source code must be modified, such as int[] arr = new int[1024*1024]; OutOfMemoryError: Java heap space will be thrown
Memory overflow error. The array created is too large and exceeds the memory allocated to the JVM.

throw keyword

effect:
You can use the throw keyword to throw the specified exception in the specified method
Use format:
throw new xxxException("cause of exception");
be careful:
1.throw keyword must be written inside the method
2. The object of new after throw keyword must be an Exception or a subclass object of Exception
3.throw keyword throws the specified exception object, and we must deal with the exception object

  • After the throw keyword, a RuntimeException or
    The subclass object of RuntimeException can not be processed. It is handed over to the JVM for processing by default (print exception object and interrupt program)

  • After the throw keyword, a compilation exception is created (an error is reported when writing code). We must deal with this exception, either throws or try... catch

Object non null judgment

public static T requireNonNull(T obj): check that the specified reference object is not null.

Source code:
    public static <T> T requireNonNull(T obj) {
        if (obj == null)
            throw new NullPointerException();
        return obj;
    }

use:

public class Demo04Objects {
    public static void main(String[] args) {
        
        method(null);
    }

    public static void method(Object obj){

        Objects.requireNonNull(obj,"The value of the object passed is null");
    }
}

throws keyword

The first way of exception handling is to leave it to others
effect:
When an exception object is thrown inside a method, we must deal with the exception object
You can use the throws keyword to handle the exception object. The exception object declaration will be thrown to the caller of the method for processing (you will not handle it yourself, but others), and finally handed over to the JVM for processing – > interrupt processing
Use format: used in method declaration
Modifier return value type method name (parameter list) throws aaaexcepton, bbbexcepton{
Throw new aaaexcepton ("cause");
Throw new bbbexcepton ("cause");
...
}
be careful:
1. The throws keyword must be written at the method declaration
2. The Exception declared after the throws keyword must be an Exception or a subclass of Exception
3. If multiple exception objects are thrown inside the method, multiple exceptions must also be declared after throws
If multiple exception objects thrown have a child parent relationship, you can directly declare the parent exception
4. If we call a method that declares that an exception is thrown, we must handle the declared exception
Or continue to use the throws declaration to throw it, give it to the caller of the method for processing, and finally give it to the JVM
Or try... catch handle the exception yourself
Example:

public class Demo05Throws {
    /*
        FileNotFoundException extends IOException extends Excepiton
        If multiple exception objects thrown have a child parent relationship, you can directly declare the parent exception
     */
    //public static void main(String[] args) throws FileNotFoundException,IOException {
    //public static void main(String[] args) throws IOException {
    public static void main(String[] args) throws Exception {
        readFile("c:\\a.xlsx");

        System.out.println("Subsequent code");
    }

    /*
        Define a method to judge the legitimacy of the transmitted file path
        If the path is not "c:\a.txt", we will throw the file and tell the caller of the method that the exception object cannot be found
        be careful:
            FileNotFoundException It is a compilation exception. If a compilation exception is thrown, it must be handled
            You can use the throws declaration to throw FileNotFoundException, an exception object, for the caller of the method to handle
     */
    public static void readFile(String fileName) throws FileNotFoundException,IOException{
        /*
            If the path passed is not at the end of. txt
            Then we throw an IO exception object to tell the caller of the method that the file suffix is wrong

         */
        if(!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }

        if(!fileName.equals("c:\\a.txt")){
            throw new FileNotFoundException("The file path passed is not c:\\a.txt");
        }

        System.out.println("There is no problem with the path,read file");
    }
}

try...catch

The second way of exception handling is to handle exceptions by yourself
Format:

    try{
        Code that may cause exceptions
    }catch(Define an exception variable,Used to receive try Exception object thrown in){
        Exception handling logic,After exception object,How to handle exception objects
        Generally at work,The exception information will be recorded in a log
    }
    ...
    catch(Exception class name variable name){

    }

be careful:
1.try may throw multiple exception objects, so you can use multiple catch es to handle these exception objects
2. If an exception occurs in try, the exception handling logic in catch will be executed, the processing logic in catch will be executed, and the code after try... Catch will continue to be executed
If there is no exception in try, the exception handling logic in catch will not be executed, the code in try will be executed, and the code after try... Catch will continue to be executed
Example:

public class Demo01TryCatch {
    public static void main(String[] args) {
        try{
            //Code that may cause exceptions
            readFile("d:\\a.tx");
            System.out.println("Resource release");
        }catch (IOException e){//catch defines exception variables to receive exception objects thrown in try
            //Exception handling logic, how to handle the exception object after the exception object
            //System.out.println("catch - the file suffix passed is not. txt");

            /*
                Throwable Class defines three exception handling methods
                 String getMessage() Returns a short description of this throwable.
                 String toString() Returns the detailed message string for this throwable.
                 void printStackTrace()  JVM This method is used by default to print exception objects. The printed exception information is the most comprehensive
             */
            //System.out.println(e.getMessage()); / / the suffix name of the file is incorrect
            //System.out.println(e.toString()); / / rewrite toString java.io.IOException of Object class: the suffix name of the file is incorrect
            //System.out.println(e);//java.io.IOException: the suffix name of the file is incorrect

            /*
                java.io.IOException: The suffix of the file is incorrect
                    at com.itheima.demo02.Exception.Demo01TryCatch.readFile(Demo01TryCatch.java:55)
                    at com.itheima.demo02.Exception.Demo01TryCatch.main(Demo01TryCatch.java:27)
             */
            e.printStackTrace();
        }
        System.out.println("Subsequent code");
    }

    /*
       If the path passed is not at the end of. txt
       Then we throw an IO exception object to tell the caller of the method that the file suffix is wrong

    */
    public static void readFile(String fileName) throws IOException {

        if(!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }

        System.out.println("There is no problem with the path,read file");
    }
}

finally code block

Format:

      try{
            Code that may cause exceptions
        }catch(Define an exception variable,Used to receive try Exception object thrown in){
            Exception handling logic,After exception object,How to handle exception objects
            Generally at work,The exception information will be recorded in a log
        }
        ...
       catch(Exception class name variable name){
 }finally{
            It is executed regardless of whether an exception occurs
        }

be careful:
1.finally cannot be used alone, but must be used together with try
2.finally is generally used for resource release (resource recovery). No matter whether the program is abnormal or not, it should finally release resources (IO)
3. If finally has a return statement, always return the result in finally to avoid this situation!

Example:

public class Demo02TryCatchFinally {
    public static void main(String[] args) {
        try {
            //Code that may generate exceptions
            readFile("c:\\a.tx");
        } catch (IOException e) {
            //Exception handling logic
            e.printStackTrace();
        } finally {
            //Whether an exception occurs or not, it is executed
            System.out.println("Resource release");
        }
    }

    /*
       If the path passed is not at the end of. txt
       Then we throw an IO exception object to tell the caller of the method that the file suffix is wrong

    */
    public static void readFile(String fileName) throws IOException {

        if(!fileName.endsWith(".txt")){
            throw new IOException("The suffix of the file is incorrect");
        }

        System.out.println("There is no problem with the path,read file");
    }
}

Handling of multiple exceptions using capture

  1. Multiple exceptions are handled separately.
  2. Multiple exceptions are captured once and processed multiple times.
  3. Multiple exceptions are captured and processed at a time.
public class Demo01Exception {
    public static void main(String[] args) {
      
              //1. Handle multiple exceptions separately.
       try {
            int[] arr = {1,2,3};
            System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }

        try{
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }

        //2. Multiple exceptions are captured at one time and processed multiple times.
        try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }

        /*
            Precautions for one try multiple catch es:
                catch For the exception variable defined inside, if there is a child parent relationship, the exception variable of the child class must be written above, otherwise an error will be reported
                ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
         */
        try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }

        //3. Multiple exceptions are captured and processed at one time.
        try {
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
            List<Integer> list = List.of(1, 2, 3);
            System.out.println(list.get(3));//IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch (Exception e){
            System.out.println(e);
        }

        //The runtime exception is thrown and can not be handled. Neither capture nor declare throw.
        //The default is for the virtual machine to process and terminate the program. When will the runtime exception not be thrown and continue to execute the program
        int[] arr = {1,2,3};
        System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
        List<Integer> list= List.of(1, 2, 3);
        System.out.println(list.get(3));//Inde = List.of(1, 2, 3);xOutOfBoundsException: Index 3 out-of-bounds for length 3

        System.out.println("Subsequent code!");
    }
}

Exception of child parent class:

  • If the parent class throws multiple exceptions, when overriding the parent class method, the child class throws the same exception as the parent class, or the child of the parent class exception, or does not throw an exception.
  • The parent class method does not throw an exception, and the child class cannot throw an exception when overriding the parent class method. At this time, the subclass generates the exception, which can only be caught and processed, and cannot be declared and thrown
    be careful:
    When the parent class is abnormal, the child class is abnormal
public class Fu {
    public void show01() throws NullPointerException,ClassCastException{}
    public void show02() throws IndexOutOfBoundsException{}
    public void show03() throws IndexOutOfBoundsException{}
    public void show04() throws Exception {}
}

class Zi extends Fu{
    //1. When the subclass overrides the parent class method, it throws the same exception as the parent class
    public void show01() throws NullPointerException,ClassCastException{}
    //2. When a subclass overrides the parent method, the subclass that throws the parent exception
    public void show02() throws ArrayIndexOutOfBoundsException{}
    //3. When the subclass overrides the parent method, no exception is thrown
    public void show03() {}

    /*
        4.1 The parent class method does not throw an exception, and the child class cannot throw an exception when overriding the parent class method.

     */
    //public void show04() throws Exception{}

    //4.2 at this time, the subclass generates the exception, which can only be caught and processed, and cannot be declared and thrown
    public void show04()  {
        try {
            throw  new Exception("Compile time exception");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Custom exception class:

The exception classes provided by java are not enough for us to use. We need to define some exception classes ourselves
Format:

public class XXXExcepiton extends Exception | RuntimeException{
     Construction method of adding an empty parameter
     Add a constructor with exception information
 }

be careful:
1. Custom Exception classes generally end with Exception, indicating that this class is an Exception class
2. Custom Exception class, which must inherit Exception or RuntimeException
Inherit Exception: the custom Exception class is a compile time Exception. If a compile time Exception is thrown inside the method, you must handle the Exception, either throw or try... catch
Inheriting RuntimeException: the custom exception class is a runtime exception that needs no processing and is handed over to the virtual machine for processing (interrupt processing)

public class RegisterException extends /*Exception*/ RuntimeException{
    //Construction method of adding an empty parameter
    public RegisterException(){
        super();
    }

    /*
        Add a constructor with exception information
        Looking at the source code, it is found that all exception classes will have a constructor with exception information. The constructor with exception information of the parent class will be called inside the method to let the parent class handle the exception information
     */
    public RegisterException(String message){
        super(message);
    }
}

Keywords: Java

Added by n_wattam on Sat, 18 Sep 2021 22:11:50 +0300