Exceptions and their handling and use

Everyone may be familiar with exceptions. When testing a program, abnormal behaviors that occur during execution are called exceptions, and the red characters that pop up are the manifestations of exceptions. Through this article, let’s take a look at exceptions. Analysis. Divide it into the following four parts!

1. Recognize anomalies

There are many types of exceptions, and different types have different handling methods.

1.1 Common exception examples

a. When the divisor is 0. (Arithmetic exception)
Everyone must know that the divisor cannot be 0. When writing the code, if the divisor is written as 0 by mistake, an exception will be reported. Not much to say, go to the code.

System.out.println(3/0);
//执行后你会发现这样一行红色的代码
Exception in thread "main" java.lang.ArithmeticException: / by zero

ArithmeticException is an arithmetic exception. The / by zero after ArithmeticException: is the reason for your error: the divisor cannot be 0.
b. Array subscript out of bounds (array subscript out of bounds exception)
Suppose the length of the array is 5, and the array's size is 5. The access range is [0,4], which starts from subscript 0 and ends at subscript (size-1). If you access beyond this range, you will see the familiar red code again. For example my code below.

int[] arr={
    
    1,2,3,4,5};
System.out.println(arr[5]);
//执行后,不好意思,爆红了.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

ArrayIndexOutOfBoundsException Array subscript out of bounds exception, this exception is very common, and the occurrence rate is quite high, if the brothers are not careful when writing code, there will be errors.
c. Access to null objects (null pointer exception).

public class Test{
    
    
	int num=1;
	public static void main(String[] args){
    
    
		//让这个引用t指向null.
		Test t=null;
		System.out.println(t.num);
	}
}
//执行后会出现异常
Exception in thread "main" java.lang.NullPointerException

NullPointerException is a null pointer exception.

Note: After an exception occurs in the program, the code behind the exception will not be executed.
Code demonstration:

System.out.println("hello world");
System.out.println(10/0);
System.out.println("hello,hello");

//执行结果

hello world
Exception in thread "main" java.lang.ArithmeticException: / by zero

1.2 Defensive programming (for the time being)

Errors exist objectively in the code, so we need to notify the programmers in time when there is a problem with the program.
We have two main ways. LBYL, EAFP
LBYL: Look Before You Leap: Do a full check before the operation.
EAFP: It's Easier to Ask Forgiveness than Permission, do it first, and then deal with it when you encounter a problem.
For example, you can understand it at a glance:
the first situation: You and your sister go to a haunted house, you are more cowardly, and you want to pull The girl's hand goes to ask the girl, wait until the girl agrees and hold hands (LBYL).
The second situation: the girl's attention is highly concentrated. At this time, you suddenly pull her hand. The big deal is that she is scared and slaps you, you Another apology is. (EAFP).
The core idea of ​​our anomaly is EAFP.

2. Basic usage of exceptions.

Let's handle exceptions.

2.1 Catching exceptions

//基本语法:
try{
    
    
	//...
}catch(异常类型,异常对象){
    
    
	//...
}finally{
    
    
	//...
}

The a.try code block is for the code that may cause an exception. The
b.catch code block is for the processing behavior after the exception occurs.
The code in the c.finally code block is used to handle the aftermath and will be executed at the end.
d. Both catch and finally can be added or not added according to the situation.

Example 1: Unhandled Exception

System.out.println("hello world");
System.out.println(10/0);
System.out.println("hello,hello");
//执行结果
hello world
Exception in thread "main" java.lang.ArithmeticException: / by zero

Example 2: After catching with try catch

try{
    
    
	System.out.println("hello world");
	System.out.println(10/0);
}catch(ArithmeticException e){
    
    
	e.printStackTrace();
}
System.out.println("hello,hello");
//执行结果:
hello world
hello,hello
java.lang.ArithmeticException: / by zero
	at demo01TimeAndSpace.Test.main(Test.java:7)

It can be found that the code statement following the exception can be executed after the exception is caught.

2.2 Exception Handling Process

a. The program executes the code in the try first.
b. If the code in the try has an exception, it will end the code in the try to see if it matches the exception type in the catch.
c. If a matching exception type is found, the catch will be executed. The code in
d. If no matching exception type is found, the exception will be passed up to the upper caller.
e. Whether or not a matching exception type is found, the code in finally will be executed (before the method ends) f .
If the upper-level caller has not handled the exception, it will continue to pass up.
g. Until the main method has no suitable code to handle the exception, it will be handed over to the JVM for processing, and the program will terminate abnormally.

2.3 Throwing exceptions

In addition to Java's built-in classes that throw exceptions, we can also throw an exception manually, using the throw keyword to accomplish this.
Syntax:

throw new 异常类型(可以写一些注释);

way to complete an x/y

public class Test {
    
    
    public static int divide(int x,int y){
    
    
        if (y==0){
    
    
            throw new ArithmeticException("除数为 0 异常");
        }
        return x/y;
    }
    public static void main(String[] args) {
    
    
        int num=divide(20,0);
        System.out.println(num);
    }
}

When we call this method and accidentally set y to 0, the following happens.

Exception in thread "main" java.lang.ArithmeticException: 除数为 0 异常
	at demo01TimeAndSpace.Test.divide(Test.java:6)
	at demo01TimeAndSpace.Test.main(Test.java:11)

2.4 Exception description

When we handle exceptions, we usually want to know what possible exceptions will occur in this code.
We can use the throws keyword to explicitly mark the exceptions that may be thrown at the position of the method definition. Thus reminding the caller to Be careful to catch these exceptions.
Look directly at the example:

public static int divide(int x,int y) throws ArithmeticException{
    
    
     if (y==0){
    
    
         throw new ArithmeticException("除数为 0 异常");
     }
     return x/y;
 }

2.5 Notes on finally

The code in finally is guaranteed to be executed. But it will also bring some trouble, let's see a code.

public static int func() {
    
    
 	try {
    
    
 		return 10;
 	}finally {
    
    
 		return 20;
 	}
}
//方法被调用后结果为:
//20.

The timing of finally execution is before the method returns:
if there is a return in try or catch, finally will be executed before the return.

However, if there is also a return statement in finally, then the return in finally will be executed, so that the original return in try will not be executed.
Therefore, it is generally not recommended to write a return statement in finally.

3. Abnormal system

insert image description here

a. The top-level class Throwable derives two important subclasses, Error and Exception
b. Error refers to Java runtime internal errors and resource exhaustion errors. Applications do not throw such exceptions. Once such internal errors occur, In addition to informing the user and causing the program to terminate, there is no power. This situation rarely occurs. (It is equivalent to a person who has a cancer, or the kind that cannot be cured at an advanced stage )
c. Exception is the exception used by our programmers The parent class of the class.
d. Exception has a subclass called RuntimeException, which derives many of our common exception classes NullPointerException, IndexOutOfBoundsException , etc.

The Java Language Specification calls all exceptions derived from the Error class or RuntimeException class as checked exceptions , and all other exceptions as unchecked exceptions

If there is a checked exception in the code, it must be explicitly processed. If it is not processed, the compilation will fail.
And the method we have given above. It is 2.3 and 2.4 , using the throw keyword or throws keyword for processing .

4. Custom exception class.

There are already very rich exception classes in the Java library, but in actual scenarios, we may want to create an exception class that meets our requirements, that is, a custom exception class. It inherits from the Exception class.
Let's take an example of simulating user login It:
in the realization of the user login function, the user may have a wrong user name input or a wrong password input. At this time, when we deal with it, we need to throw two exceptions, namely the user name input error exception and the password input exception. Error exception to remind customers.

Custom username input exception:

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

Custom password input exception:

public class PasswordException extends Exception{
    
    
    public PasswordException(String message) {
    
    
        super(message);
    }
}

For the specific implementation, let's give a complete code:

import java.util.Scanner;

public class Login {
    
    
    String name="admin";
    String password="123456";

    public boolean loginInfo(String n,String p){
    
    
        if (!name.equals(n)){
    
    
        	//如果输入的用户名和我们所给的不一样,会抛异常
           throw new UserException("用户名输入有误");
        }
        if (!password.equals(p)){
    
    
        	//如果输入的密码和我们所给的不一样,会抛异常
           throw new PasswordException("密码输入有误");
        }
        return true;
    }
    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);
        String s1=sc.next();
        String s2=sc.next();
        Login login=new Login();
        login.loginInfo(s1,s2);
        System.out.println("login ok");
        sc.close();
    }
}

Guess you like

Origin blog.csdn.net/weixin_47278183/article/details/121033422