Java development - 20 abnormal

Exception:

It refers to the abnormal situation during the execution of the program, which will eventually lead to the abnormal stop of the Java virtual machine (JVM).

In object-oriented programming languages such as Java, the exception itself is a class. Generating an exception is to create an exception object and throw an exception object. The way Java handles exceptions is interrupt handling.

Note: exceptions do not refer to syntax errors. If the syntax is wrong and the compilation fails, bytecode files will not be generated and cannot run at all.

Sorting out learning ideas:

Throwable system:

Error: serious error, which cannot be handled and can only be avoided in advance;

Exception: indicates an exception. After an exception occurs, the programmer can correct it through code to make the program continue to run, which must be handled; It's very timely. We usually encounter it.

Classification of exceptions:

Exceptions are divided into compiled exceptions (non RuntimeException) and non compiled exceptions (RuntimeException);

Compilation exception: the code cannot run correctly and cannot be generated The bytecode file of class is just like that non static variables cannot be defined in static methods... It will become popular when using Java development tools, resulting in compilation failure.

Non compiled exception: the code can run correctly and generate the corresponding bytecode file, but it will report an error when running, just like the null pointer exception we usually encounter

Exception handling:

1. Output the name, cause and location of the exception on the console

2. Program stop

How to handle non compiled exceptions (runtime exceptions):

Throw exceptions:

(throws exception name, which throws the exception and the java virtual opportunity handles the relevant exception);

Catch exception:

(try {possible exception code block;} Catch (exception class name) {handling method;}) And handle it manually;

There are two different treatment methods:

Display of exception throwing Code:
public class test {

    public static void main(String[] args) {

        int a = 0;
        int b = 1;
        
        //The divisor cannot be 0. If the divisor is 0, an exception will be reported
        System.out.println(b/a);

    }

}

I didn't throw an exception here. The underlying Java JVM helps us judge and handle it. The Java JVM will automatically help us find the exception class corresponding to the exception and throw an exception;

Throwing an exception does not actually solve the exception, but has the Java JVM to find the relevant exception class and throw it. Therefore, if some problems cannot be avoided in the later code development process, you can throw relevant exceptions for the user's attention, because there will be a lot of uncertainty if you connect with the user;

In the DateFormat abstract class of Java, the parse() method in the SimpleDateFormat implementation class has an exception to throw;

//Parses text from the beginning of a given string to generate a date. This method may not use the entire text of a given string
public Date parse(String source)
           throws ParseException
           //ParseException - if the beginning of the specified string cannot be parsed.
Display of exception capture code:

try... catch exception:

 public static void main(String[] args) {

        try {

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

        }catch (ArithmeticException e){

            System.out.println("Pay attention to the divisor");

        }
    }

thorw keyword:

Java provides a throw keyword, which is used to throw a specified Exception object (you can make a custom Exception object); The following methods cannot throw an Exception, which is a broad Exception.

Specify the problems that may occur when throwing an exception: (exception mismatch)

The difference between throw and throws:

1.throw stands for action, which means the action of throwing an exception; throws represents a state and indicates that the method may throw an exception;

2.throw is used in method implementation, and throws is used in method declaration;

3.throw can only be used to throw a specified exception, while throws can throw multiple exceptions;

The keyword throws is used on the method declaration to indicate that the current method does not handle exceptions, but reminds the caller of the method to handle exceptions (throw exceptions).

Custom exception:

Custom exceptions are unavoidable errors when we write code. They are reminded to users when calling. Custom exceptions usually inherit from Exception/RuntimeException. You can refer to Exception when customizing. The bottom layer inherits Throwable.

Ring by ring...:

Custom age exception class:

//Define Student class
public class Student {

    private String name;
    private String sex;
    private int age;

    public Student() {
    }

    public Student(String name, String sex, int age) {
        this.name = name;
        this.sex = sex;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
}
}

Define the age exception class (when the age is less than 0, the StudentAgeException exception will pop out, so it is an exception, inherited from the RuntimeException class):

public class StudentAgeException extends RuntimeException{

    public StudentAgeException() {
        super();
    }
    public StudentAgeException(String mess) {
        super(mess);

    }
}

Test:

import cn.xiaozheng.pojo.Student;

public class StudentTest {

    public static void main(String[] args) {

        Student student = new Student();

        student.setAge(-2);

        if(student.getAge() < 0){
            throw new StudentAgeException("The age entered cannot be less than 0");
        }

        System.out.println(student.getAge());
    }

}

Note: the exceptions we define now cannot be thrown with try... catch, because the conditions for throwing exceptions are not defined in our exception class, just to prevent some known exceptions, so we can only use relevant judgment + throw to throw the specified exceptions.

finally keyword:

In the previous study of the final keyword, a finally keyword is extended. It is used in try... catch to indicate that the content in the finally code block will be output whether there is an exception or not;

Some statements do not execute, causing the program to throw exceptions. Finally solves this problem. The code stored in the finally code block will be executed.

As for the exception in the above picture, the sound code after the exception does not execute the output. Finally is to solve the problem. The content to be output after the exception occurs will be placed in the finally block.

For example, for the File class to be learned later, whether it is an input stream or an output stream, the stream must be closed after the program runs to release resources. If an exception occurs and the resource cannot be released, resulting in Java memory overflow, an error will be reported, so finally is necessary.

fianlly definition format:

//Writing format:
try {
  Possible exception codes;
      . . . 
} catch(Exception class name variable name) {
  Exception handling code;
} finally{
    Release resources
}
//matters needing attention
finally Cannot be used alone. Must cooperate try...catch use

Code demonstration:

public static void main(String[] args) {

        try {
            int num [] = {1,2,3};
            //num = null;
            System.out.println(num[2]);
        }catch (NullPointerException e){
        
            throw new NullPointerException();
            
        }finally {
        
            System.out.println("Must execute me!!!");
        }

        System.out.println("I am try...catch Content outside");
    }

Scenario Display:

If you return directly in the try, finally will execute and will not affect the final output. (when learning the return keyword in the early stage, we know that return is the end method, so there is no content after return.)

About the order of output: finally, it is output before return. According to the original meaning, there is no content output after return, so the return execution must be the last.

public class DemoFinally {

    public static void main(String[] args) {

        System.out.println(new DemoFinally().test());
    }
    
    //In order to see the effect, I mentioned the original content into the method, so that return can return the content and see the effect intuitively.
    public String test(){
        try {

            int num [] = {1,2,3};
            //num = null;
            System.out.println(num[2]);

            return "Method execution completed!";

        }catch (NullPointerException e){

            throw new NullPointerException();

        }finally {

            System.out.println("Must execute me!!!");
        }
    }

Tags: Java JavaEE

Posted by sonic_2k_uk on Mon, 02 May 2022 17:46:38 +0300