Java Foundation (exception)

1: Basic knowledge points of exceptions

(1) What is the exception?

     1. Anomalies simulate "abnormal" events in the real world.

     2.java uses "classes" to simulate exceptions.

     3. Class can create objects.

         NullpointerException e = 0*12345;

e is the reference type, and the memory address saved in e points to the "object" in the heap

This object must be of type NullpointerException

NullpointerException is a type of exception

For example, "robbery" is a kind of exception - >

"Zhang San was robbed" is an abnormal event - > object

(2) What is "call stack"?

There is a calling relationship between methods, which can be described by "call stack" There is a memory space called "virtual machine stack" in the JVM to store the calling relationship between methods When an exception occurs in the code, we can use e.printStackTrace(); View the call stack with exception code

(3) Contacted exception

1. Denominator is 0

System.out.println(10 / 0);
// results of enforcement
Exception in thread "main" java.lang.ArithmeticException: / by zero

2. Array subscript out of bounds

int[] arr = {1, 2, 3};
System.out.println(arr[100]);
// results of enforcement
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100

 3. Accessing null objects

public class Test {
    public int num = 10;
    public static void main(String[] args) {
        Test t = null;
        System.out.println(t.num);
   }
}
//Execution results:
Exception in thread "main" java.lang.NullPointerException

(4) Two kinds of exception defense programming

1.LBYL: Look Before You Leap. Make adequate checks before operation

2.EAFP: It's Easier to Ask Forgiveness than Permission. It's easier to get forgiveness afterwards than to get permission in advance That is, operate first and deal with problems later (is the core idea of anomaly)

(5) Inheritance of exceptions (see exception architecture below)

2: Basic usage of exceptions

(1) Catch exception (try... catch...)

1. Basic grammar:

try{ 
 Statements with possible exceptions ; 
}[catch (Exception type exception object) {
} ... ]
}[catch (Exception type exception object) {
} ... ]
}[catch (Exception type exception object) {
} ... ]
[finally {
 Abnormal exit
}]
//A catch can have one or more

Explanation:

The try code block contains the code that may cause exceptions

The catch code block contains the handling behavior after an exception occurs

finally, the code in the code block is used to deal with the aftermath and will be executed at the end

catch and finally can be added or not according to the situation

2. Code example

Do not handle exceptions: once an exception occurs, the program terminates and cannot correctly output the contents after the exception

int[] arr = {1, 2, 3};//Length 3
System.out.println("before");
System.out.println(arr[10]);
System.out.println("after");
// results of enforcement
before
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
//after has no output

Use (try... catch...) Handling exceptions

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {//subscript out of bounds
    // Print the call stack with exception
    e.printStackTrace();
}
System.out.println("after try catch");
// results of enforcement
before
java.lang.ArrayIndexOutOfBoundsException: 100
 at demo02.Test.main(Test.java:10)
after try catch

Note: once an exception occurs in try, the program in the try code block will not continue to execute, but will be executed by the code in catch After the catch is executed, it will continue to execute

catch cannot handle null pointer exception

Code example:

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    arr = null;//Null pointer
    System.out.println(arr[100]);
    System.out.println("after");
} catch (ArrayIndexOutOfBoundsException e) {
    e.printStackTrace();
}
System.out.println("after try catch");
// results of enforcement
before
Exception in thread "main" java.lang.NullPointerException
 at demo02.Test.main(Test.java:11

Note: after try catch is not executed in the result, indicating that the catch statement cannot catch the null pointer exception just now Because the exception types do not match.

catch can only use one (not recommended)

Code example:

int[] arr = {1, 2, 3};
try {
    System.out.println("before");
    arr = null;
    System.out.println(arr[100]);
    System.out.println("after");
} catch (Exception e) {//Exception is the parent class
    e.printStackTrace();
}
System.out.println("after try catch");
// results of enforcement
before
java.lang.NullPointerException
 at demo02.Test.main(Test.java:12)
after try catch

Note: NullPointerException and ArrayIndexOutOfBoundsException are subclasses of Exception, so they can be caught.

(2) Throw keyword throw up exception

1. Usage: when defining a method, you can use the throws keyword to declare it. A method declared with the throws keyword means that the method does not handle exceptions and is handed over to the method call for processing.

2. Syntax example:

public Return value type method name (parameter list,,) throws Exception class{};

3. Code example:

public static void main(String[] args) {
    System.out.println(divide(10, 0));
}
public static int divide(int x, int y) {
    if (y == 0) {
        throw new ArithmeticException("Throw exception except 0");
   }
    return x / y;
}
// results of enforcement
Exception in thread "main" java.lang.ArithmeticException: Throw exception except 0
 at demo02.Test.divide(Test.java:14)
 at demo02.Test.main(Test.java:9)

(3) What is the role of the anomaly mechanism?

After an abnormal event occurs in the program, it outputs detailed information for us. Through this information, programmers can deal with the program to make the program more robust.

Code example:

int a = 10;
int b = 0;
if(b != 0){
   int c = a/b;
   System.out.println(a + "/" + b "=" + c);
}else{
   System.out.println("Divisor cannot be 0");
 }

3: Exception architecture of java

1. Inheritance relationship between Java built-in exception classes:

2. Interpretation:

The top-level class Throwable derives two important subclasses, Error and Exception.

Error refers to Java runtime internal error and resource exhaustion error The application does not throw such an exception Once this internal error occurs, there is nothing to do but inform the user and terminate the program This rarely happens.

Exception is the parent of the exception class used by our program.

Exception has a subclass called RuntimeException, which derives many common exception classes, such as NullPointerException, indexoutofboundsexception, etc.

4: Custom exception class

1. Definition: in addition to the exception class in java, there may be some situations in our actual scenario that require us to extend the exception class and create exceptions that meet our actual situation.

2. Code example:

public class Test {
    private static String userName = "admin";
    private static String password = "123456";
    public static void main(String[] args) {
        login("admin", "123456");
   }
    public static void login(String userName, String password) {
        if (!Test.userName.equals(userName)) {
            // TODO processing user name error
       }
        if (!Test.password.equals(password)) {
            // TODO processing password error
       }
        System.out.println("Login successful");
   }
}

3. Note:

Custom exceptions usually inherit from Exception or RuntimeException.

Exceptions inherited from Exception are checked exceptions by default.

Exceptions inherited from RuntimeException are non checked exceptions by default.

Keywords: Java Back-end

Added by moffo on Sat, 08 Jan 2022 13:45:09 +0200