Java exception handling

exception handling

Top class of Throwable exception handling class

Error (server crash database crash)

Exception (exception class): runtimeException (runtime exception)

        // Corner sign out of range
        int[] num = new int[1];
        System.out.println(num[2]);

        //ArrayIndexOutOfBoundsException
        // Null pointer exception
        int[] num = new int[1];
        num = null;
        System.out.println(num[1]);

        // NullPointerException
        // Arithmetic abnormality
        // ArithmeticException
        System.out.println(10/0);

try....catch....finally

   try refers to the test exception code
   catch refers to capturing exception information
   finally refers to the execution after the end of the exception


  try...catch the process of catching exceptions

  1. An exception occurred in a code in the function
  2. If an exception occurs, the corresponding exception object will be generated
  3. This exception object is returned to the caller
        Case 1: if the exception is not handled, the exception will be handed over to the superior
                Leave it to the JVM to handle the JVM using the default processing mechanism
        Case 2: the caller performs exception handling (try...catch)
                The returned exception object will match the catch
                Match statements in catch executed successfully
// Test exception
class TestException{
    // Division returns the quotient of two numbers
    public int fun(int a , int b) {
        // If an exception occurs, a corresponding exception object will be generated
        // new ArithmeticException("/ by zero")
        return a / b ;
    }
}
    public static void main(String[] args) {
        TestException testException = new TestException();
        try {
            // Code with possible exception
            int num = testException.fun(10, 0);
            System.out.println(num);
        }catch (Exception e) {
            // Catch exception
            // The exception to be caught in parentheses
            System.out.println("You have 0");
        }
        System.out.println("!!!");
    }

Multi catch handling exception

        int[] arr = new int[4];

        try {
            // The out of range exception of the report results in the object of out of range exception
            System.out.println(arr[5]);
            arr = null;
            System.out.println(arr[1]);
            System.out.println(10/0);
        }catch (ArrayIndexOutOfBoundsException e) {
            // When a catch is matched again, other catches will not be matched
            System.out.println("You crossed the line");
        }catch (NullPointerException e) {
            System.out.println("You have no pointer");
        }catch (ArithmeticException e) {
            System.out.println("You're out of zero");
        }catch (Exception e) {
            // Note!! if you want to write exception to catch
            //          It needs to be placed below and the exception in catch should be from small to large
            System.out.println("???");
        }System.out.println("!!!");

finally

Whether there is an exception or not will not affect the execution of finally
 finally: generally used to close resources, close streams and close databases
class TestFinally{
    // What is the num returned when the method is called?
    public int fun() {
        int num = 10;
        try {
            num = 20;
            System.out.println(9/3);
            return num;
        } catch (Exception e) {
            // Catch exception
            num = 30;
            // Establishing a return path is equivalent to having a box
            // What is stored in the box is the returned value
            // Not directly. return will see if it is finally
            // Execute if there is finally, but it will not change if it is already in the path
            // Wait until finally finishes executing, and then return completely
            return num;
        } finally {
            num = 40;
            // It is meaningless to write only closed resources and return in finally
            // The previous return values will be overwritten
            // return num;
        }

    }
}

    try {
            System.out.println(1/1);
            // Even if the return method finally executes
            // Close the JVM finally directly and it will not execute
            return;
        } catch (Exception e) {
            System.out.println("You're out of zero");
        } finally {
            System.out.println("????????");
        }
        System.out.println("!!!!!");

Runtime and compile time exceptions

    FileInputStream i = new FileInputStream("wl.txt");
    try {
            FileInputStream i = new FileInputStream("wl.txt");
        } catch (Exception e) {
            System.out.println("No such file");
        }
        // Read files under this path
        // The system does not know if there are any files in your path
        // You need to ask in advance if there is no file in this path
        // Compile time exceptions are what the system forces you to handle

     //Handling method1: Add totry...catch(Manual processing)
        try {
            FileInputStream i = new FileInputStream("wl.txt");
        } catch (Exception e) {
            System.out.println("No such file");
        }
     //Handling method2: You can leave exceptions to your superiors
        // You can leave the problem to the main function and add it to the function declaration of the main function
        // The name of the exception type to throw by throws
        public static void main(String[] args) throws FileNotFoundException{
            FileInputStream i = new FileInputStream("wl.txt");
        }

The method of Throwable

    public static void main(String[] args) {
        Exception e = new Exception("Error messages can be written here");
        // Get error information
        String message = e.getMessage();
        // System.out.println(message);
        // System.out.println(e);
        // Print error message class name of error location exception class
        e.printStackTrace();
    }
    //Infinite input integer stored in set print input quit stop
    //I hope that the program can continue to run when I input the string
    public static void main(String[] args) {
        System.out.println("Please enter an integer: ");
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> arrayList = new ArrayList<>();
        while (true) {
            String string = scanner.nextLine();
            if (string.equals("quit")) {
                break;
            }
            // Handling exceptions
            try {
                // String to number
                int num = Integer.parseInt(string);
                // Add to array
                arrayList.add(num);
            } catch (Exception e) {
                System.out.println("The input is not an integer. Please re-enter");
            }
        }
        // Print at the end of the cycle
        System.out.println(arrayList);
    }

Tags: jvm Database

Posted on Mon, 04 May 2020 15:04:20 -0700 by love_php