Everyone has mistakes in life, let's take a look at the exceptions in Java! ! !

Detailed Explanation of Exception Problems in Java

1. The concept and classification of exceptions

1. Abnormal concept

Concept: A Java exception is an object that describes an exception that occurs in a code segment. When an exception occurs, an object representing the exception is created and thrown in the method that caused the exception, and the method can choose to handle the exception itself Or pass that exception.

Exception mechanism: The exception mechanism refers to how the program handles when an error occurs in the program. Specifically, the exception mechanism provides a safe channel for program exit. When an error occurs, the flow of program execution changes, and the control of the program is transferred to the exception handler.

2. About the classification of abnormalities

(1) Non-checked exception (runtime exception): refers to the exception that occurs during program execution

Example Demo:

int[] array = null;
System.out.println(array.length);

//执行结果:
Exception in thread "main" java.lang.NullPointerException
	at TestDemo.main(TestDemo.java:160)
//必须对其进行捕获或声明以便抛出    

(2) Checked exception (compile-time exception): refers to the exception that occurs when the program is compiled

(3) Logic error: It means that the program is not executed in the expected logical order. Exception means that errors occur when the program is running, and exception handling is to handle and control these errors

3. Common exceptions

(1) Arithmetic exception

Demo:

int a = 10;
System.out.println(a/0);


//执行结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
//0不能放在分母    

(2) Array out of bounds exception

Demo:

int[] array = {
    
    1,2,3};
System.out.println(array[4]);


//执行结果:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3

(3) Null pointer exception

Demo:

int[] array = null;
System.out.println(array.length);


//执行结果:
Exception in thread "main" java.lang.NullPointerException

2. Abnormal Architecture

​In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specifies the commonality of any problem that is conveyed through a Java application by an exception propagation mechanism available in the code.

insert image description here

It can be seen in the figure

  • Throwable: There are two important subclasses: Exception (exception) and Error (error), both of which are important subclasses of Java exception handling, each containing a large number of subclasses. The difference between exceptions and errors is that exceptions can be handled by the program itself, but errors cannot be handled.
  • Error: Refers to serious problems that the Java virtual machine cannot solve, such as: JVM internal errors, resource exhaustion, etc. Typical representatives: StackOverflowError and OutOfMemoryError.
  • Exception: It is an exception that the program itself can handle. The Exception class has an important subclass RuntimeException. The RuntimeException class and its subclasses represent errors thrown by "common operations of the JVM".
  • Exception: Divided into runtime exceptions and non-runtime exceptions.

3. Exception handling

1. Defensive handling

Defensive processing means that programmers must have this awareness when writing code, and a check will be done after writing a code.

As the following example:

Demo:

boolean ret = false;
ret = 登陆游戏();
if (!ret) {
    
    
处理登陆游戏错误;
  return;
}
ret = 开始匹配();
if (!ret) {
    
    
处理匹配错误;
  return;
}
ret = 游戏确认();
if (!ret) {
    
    
处理游戏确认错误;
  return;
}
ret = 选择英雄();
if (!ret) {
    
    
  处理选择英雄错误;
  return;
}
ret = 载入游戏画面();
if (!ret) {
    
    
处理载入游戏错误;
  return;
}

2. Post-event handling

After-the-fact error-recognition processing refers to executing the code first, and then dealing with the problem if there is a problem.

(1).try···catch···Exception capture and processing

try {
    
    
  登陆游戏();
  开始匹配();
  游戏确认();
  选择英雄();
  载入游戏画面();
 ...
} catch (登陆游戏异常) {
    
    
  处理登陆游戏异常;
} catch (开始匹配异常) {
    
    
处理开始匹配异常;
} catch (游戏确认异常) {
    
    
处理游戏确认异常;
} catch (选择英雄异常) {
    
    
处理选择英雄异常;
} catch (载入游戏画面异常) {
    
    
处理载入游戏画面异常;
}

Note:

  • Store possible exception codes in try
  • Catch possible exceptions in catch

Demo:

try {
    
    
     int a = 10;
     System.out.println(a/0);

     System.out.println("正常代码!");
}catch (ArithmeticException e) {
    
    
      e.printStackTrace();//快速地定位异常出现的位置
      System.out.println("你这里出现了算术异常!");
}

//执行结果:
java.lang.ArithmeticException: / by zero
	at TestDemo.main(TestDemo.java:161)
你这里出现了算术异常!

From the above results, it can be seen that when the code runs to the wrong code, an exception will be thrown, and the catch will catch the exception, and it will not continue to execute the following normal code

Details about the use of try···catch···

(1) If there are multiple exceptions in the try, you can use '|' to separate each exception when the catch catches it.

catch (ArithmeticException | NullPointerException e)

(2) If the corresponding exception is not written in the catch, it will not be caught here, and eventually the exception will be handed over to the JVM for processing, the program will terminate immediately, and normal code will not be executed.

(3) Two or more abnormalities will not occur at the same time

Reason: Because when an exception occurs, it will be caught directly by catch, and the statement in try will not continue to be executed.

(4) It is not recommended to write like this

catch(Exception e) {}

Writing like this shows that you are lazy! ! !

(5) Multiple different exception objects may be thrown at the same time in the try, and multiple catches must be used to catch them - multiple exceptions, multiple captures.

(6)

catch(Exception e) {
    
    
            
}catch(ArithmeticException e) {
    
    
            
}

Since Exception is the parent class of all classes, there is no need for the subsequent subclasses to exist, so this way of writing is not feasible! ! !

But this way of writing is feasible when the parent class Exception and the child class exchange positions.

(2) Exception statement

After the parameter list in the method declaration, when a compile-time exception is thrown in the method, and the user does not want to handle the exception, then throws can be used to
throw the method for processing.That is, the current method does not handle exceptions, and the caller of the method is reminded to handle exceptions

Grammar format:

修饰符  返回值类型  方法名(参数列表) throws 异常类型1,异常类型2...{
    
    
    
}

Specific code example:

Demo:

public class TestDemo {
    public static void test(int a) throws CloneNotSupportedException {
        if (a == 10) {
            throw new CloneNotSupportedException();
        }
        System.out.println("异常后的代码不执行!");
    }
    public static void main(String[] args) {
        try {
            test(10);

            System.out.println("正常代码!");
        }catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}

//执行结果:
java.lang.CloneNotSupportedException

Precautions:

  • throw must be written inside the method body
  • The thrown object must be an object of Exception or a subclass of Exception
  • If it is a Runtime Exception or a subclass of Runtime Exception, you don't have to deal with it, just leave it to the JVM
  • If a compilation exception is thrown, it must be handled, otherwise the compilation will not pass
  • Once an exception is thrown, the code behind the exception will not be executed

(3) About the finally keyword

finally: generally used for resource release, disconnection, closing pipeline flow, etc.

It is generally used with try-catch --finally or try-finally. Generally speaking, finally will be executed regardless of whether an exception is thrown in try.

Demo:

public class TestDemo {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        try {
    
    
           int num = scanner.nextInt();
            System.out.println(num);
        }catch (InputMismatchException e) {
    
    
            e.printStackTrace();
            System.out.println("输入的数据不匹配!");
        }finally {
    
    
            System.out.println("执行了finally部分,一般用来关闭资源!");
            scanner.close();
        }
    }
}

insert image description here

This is the correct input.

insert image description here

This is wrong input. The code tells us to enter a number, but here we enter a string, and an input exception will occur.

But the code in the finally part will be executed regardless of whether there is an exception

(4) About the process of exception handling

  • If there is an exception in try, it will throw an exception, caught by catch, and then match whether there is a paired exception
  • If there is, execute the statement in the catch
  • If not, the exception will be uploaded to the upper caller
  • The statement in finally will be executed regardless of whether it is present or not
  • If the upper-level caller does not have it, the upload will continue
  • Until the main method, if there is no main method, it will be handed over to the JVM, and the program will terminate abnormally at this time

(5) Notes for finally

It is recommended not to return data in finally! ! !

Because the method ends after the return in the finally block returns, the return statement in the try block will not be executed again. That is to say, the return value in the try block will be saved first, and then the return value in the try block will be returned after the code in the finally is executed, so the code logic in the finally will not affect the return value in the try block of. But if return is used in finally, the code in the try block will not be executed and the correct result will not be returned.

example:

public class TestDemo {
    
    
    public static int func() {
    
    
        int num = 10;
        try{
    
    
            return num;
        }catch (Exception e){
    
    
            e.printStackTrace();
        } finally {
    
    
            num = 5;
            return num;
        }
    }
    public static void main(String[] args) {
    
    
        int ret = func();
        System.out.println(ret);
    }
}

//执行结果:
5

4. Custom exceptions

Although Java has built-in rich exception classes, it cannot fully represent some exceptions encountered in actual development. At this time, it is necessary to maintain an exception structure that meets
our situation.

Specific ways:

Format: public class XXXException extends Exception or RuntimeException{

Add a constructor with empty parameters

Add a constructor with exception information

}

Demo example:

class UserNameErrorException extends RuntimeException {
    
    
    public UserNameErrorException() {
    
    
        super();
    }
    public UserNameErrorException(String message) {
    
    
        super(message);
    }
}
class PassWordErrorException extends RuntimeException {
    
    
    public PassWordErrorException() {
    
    
        super();
    }
    public PassWordErrorException(String message) {
    
    
        super(message);
    }
}
public class TestDemo {
    
    
    private String userName = "admin";
    private String passWord = "123456";

    public void LoginInto(String userName,String passWord) {
    
    
        try {
    
    
            if(!this.userName.equals(userName)) {
    
    
                throw new UserNameErrorException("用户名错误!");
            }
            if (!this.passWord.equals(passWord)){
    
    
                throw new PassWordErrorException("密码错误!");
            }
            System.out.println("登陆成功!");
        }catch (UserNameErrorException e) {
    
    
            e.printStackTrace();
        }catch (PassWordErrorException e) {
    
    
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
    
    
        TestDemo test = new TestDemo();
        test.LoginInto("admi","123456");
    }
}

The first running result: when userName and passWord are entered correctly

insert image description here

The second operation structure: when one or both of userName and passWord are incorrect

insert image description here

insert image description here

Precautions:

  • Custom exceptions usually inherit from Exception or RuntimeException
  • Exceptions inherited from Exception are checked exceptions by default
  • Exceptions inherited from RuntimeException are unchecked exceptions by default

all right! That’s all for the exceptions in java. If you guys have any questions or find any problems with this blog, you can send a private message! ! !

With the journey of ants, we will show our ambitions

Guess you like

Origin blog.csdn.net/m0_74968164/article/details/130612263