Java Exception Handling Mechanism (End)-I can’t understand anymore, I can’t find a girlfriend

Don't feel inferior, and improve your strength.
Who
is the best in the Internet industry? If the article can bring you energy, that's the best thing! Please believe in yourself, come
on o~

Insert picture description here

Exception handling

abnormal:

For computer programs, we do not guarantee that the programs we write will not cause any problems. Even if there are no logical errors in the program design, can you guarantee that users will legally enter data according to their wishes? Even if the user cooperates with you fairly, can you guarantee that you will not have other problems when you run the program? For example, the network is suddenly interrupted, or the power supply is interrupted.

Then we must consider these issues when designing the program to ensure that when the program runs wrong, there is a corresponding solution, instead of throwing the exception directly to the virtual machine to cause the program to terminate.

Frequent exceptions

Insert picture description here

  • IndexOutOfException: Generally, the array subscript is out of bounds exception
int[] arr=new int[10];
System.out.println(arr[20]);

Insert picture description here

  • NullPointException: Null pointer
String string=null;
string.charAt(0);

Insert picture description here

  • NumberFormatException: Numerical type conversion error
String string="abc";
Integer a=Integer.parseInt(string);

Insert picture description here

  • ArithmeticException: Arithmetic exception
int a=2;
int b=0;
a=a/b;

Insert picture description here

  • ClassCastException: Reference type conversion exception
public class Main {
    
    
    public static void main(String[] args) {
    
    
        String string="";
        Animal dog=new Dog();
        Cat cat=(Cat)dog;
    }
}
class Animal{
    
    

}
class Dog extends Animal{
    
    

}
class Cat extends Animal{
    
    

}

Insert picture description here

Exception handling mechanism

Method 1: try...catch

try {
    
    
      //执行代码
}catch (Exception e){
    
    
      //解决方案
}

For example, when we calculate 1/0, there will be arithmetic errors, we can catch arithmetic exceptions generated during the operation

try {
    
    
      int a=2/0;
}catch (ArithmeticException e){
    
    
      e.printStackTrace();
}

In this way, when encountering an arithmetic exception, our catch statement will catch the exception and solve it

  • You can use multiple catch blocks to catch multiple exceptions
  • But be careful, small exceptions are placed on the top, big exceptions are placed below
  • Because the big exception is their parent, once it is placed on it, the other small exceptions will not be executed
  • So give priority to small exceptions, so as to make the structure clear and the handling more clear

When we execute a certain statement in the try statement block to generate an exception, the code after it will not be executed, and the corresponding statement will be executed in the catch block that caught the exception.

Variables defined in the try statement block are local variables and cannot be accessed in the catch statement block

Method two: multiple exception capture

Since Java7, a catch block can catch a variety of exceptions

  • When capturing multiple exceptions, separate the multiple exception types with a vertical bar|
  • When catching multiple exceptions, the exception variable is implicitly finalized, and the exception variable cannot be re-assigned
try {
    
    
	int a=1/0;
}catch (ArithmeticException |IndexOutOfBoundsException e){
    
    
    System.out.println("程序产生了算术异常或数组越界异常");
    //e=new Exception();改段代码会报错,因为catch括号里面的变量e被final修饰,不可重新赋值
}catch (Exception e){
    
    
    e=new Exception();
}

Because the variables in the multi-exception capture mode are final modified, it is impossible to re-assign variables in the catch statement block

Method 3: try...catch...finally

When we open some files in the try statement block at some point, or connect to the database, etc., once we generate an exception in the try statement block, then our subsequent code will not be executed, resulting in files and databases It can't be closed in time.

  • Java's garbage collection mechanism does not reclaim any physical resources, only the memory occupied by objects in the heap memory

In order to ensure that the physical resources opened in the try can be recovered in time, the Java exception handling mechanism provides a finally statement block. This statement block is a code block that must be executed after the try and catch statement blocks are executed. If in try or catch The return statement will not affect the execution of finally. After the finally is executed, return is executed. If there is a return statement in the finally, then the return in the try and catch statement blocks will not be executed, but there is a point if it is in the try If it is System.exit(1), the finally statement block will not be executed, because this will cause the virtual machine to exit directly.

FileWriter file=null;
try{
    
    
      file=new FileWriter("text.txt");
}catch (IOException e){
    
    
      e.printStackTrace();
}finally {
    
    
      if(file!=null){
    
    
           try {
    
    
                file.close();
           } catch (IOException e) {
    
    
                e.printStackTrace();
		}
	}
}

In this way, if an exception occurs in the try block, the code will still execute the close method in finally to close the file

Java7, 9 enhanced try statement that automatically closes resources

When we execute the code that closes the resource in finally, the program is very bloated

Java7 :
  • Java7 enhances the function of the try statement, which allows us to follow a pair of parentheses immediately after the try, and some resources can be declared and defined in the parentheses
  • When we finish executing the try statement, the program will automatically close the resource for us
  • These resources must implement the AutoCloseable interface or the close method of the Closeable interface
  • The Close interface is a sub-interface of AutoCloseable
try (FileWriter file=new FileWriter("text.txt")) {
    
    
     file.write("");    
}catch(Exception e){
    
    
     e.printStackTrace();
}
Java9 :
  • Java9 further enhances this operation, no need to declare and define in parentheses
  • Can be defined outside the try statement
  • But the resource variable must be final or valid final, that is, it has never been assigned other values.
FileWriter file1=new FileWriter("text.txt");
FileWriter file2=new FileWriter("text.txt");
try(file1;file2){
    
    
      file.write("");
}catch(Exception e){
    
    
      e.printStackTrace();
}

Checked exception and Runtime exception

Exceptions in Java can be divided into two categories:

One is Check exception (compiled exception):

One is Runtime exception (runtime exception):

All the exceptions of the RuntimeException class and its subclasses are runtime exceptions, and the rest are compile-time exceptions

Runtime exceptions refer to exceptions that only appear after our program is running. Such exceptions do not affect compilation, but errors will occur during operation.

But when compiling, we must deal with the exception explicitly, otherwise we cannot compile, for example, when we call the sleep method in multiple threads,

We need to use try...catch to wrap it, otherwise an error will be reported, because the method throws a compilation exception when it is defined, and we need to explicitly deal with it

Use throws to throw exceptions

  • When we sometimes don’t know how to handle the exception, we need to throw the generated exception object upwards
  • The method will be thrown to the main method. If it is not resolved in the main method, it will continue to be thrown upwards
  • Throw it to the Java virtual machine, print the exception trace stack information, and terminate the program
  • This is why the program we ran before will terminate after it fails, and some red errors will be printed on the console.
public static void main(String[] args) throws IOException {
    
    
        test();
}
public static void test() throws IOException {
    
    
        int a=2/0;
}
public static void main(String[] args){
    
    
        try {
    
    
            test();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
public static void test() throws IOException {
    
    
        int a=2/0;
    }
}

note:

  • But when we call the method that throws an exception, this method is either in the try...catch block
  • Or in another method with throws
  • Because since the method throws an exception, we need to catch it and solve it

Precautions for throwing exceptions when rewriting methods

When our subclass inherits the parent class, if the method of the parent class throws an exception

When the subclass overrides this method, the exception thrown must not be greater than the exception thrown by the parent class

class A{
    
    
    public void test() throws ArithmeticException{
    
    
        
    }
}
class B extends A{
    
    
    @Override
    public void test() throws Exception {
    
    
        
    }
}

The above code will report an error, because the Exception thrown by the subclass B is larger than the exception thrown by the parent class

Use throw to throw an exception

In some situations, it may not be a real anomaly, as long as it is an idea that does not meet our expectations, it is an anomaly

When it does not meet expectations, we can manually throw an exception

public static void main(String[] args){
    
    
        int a=-1;
        try {
    
    
            if(a<0){
    
    
                throw new Exception("a为负数");
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
        }
        
    }

For Check exception, we either explicitly catch it, or continue to throw

The Runnable exception, we can either explicitly catch it or ignore it

Custom exception class

Because the exceptions defined by Java are limited, sometimes it does not meet our needs. At this time, we need to define an exception class by ourselves to achieve the functions we need.

  • First of all, we must inherit the Exception class or the base class such as RuntimeException
  • Then define two constructors
  • The parameterized constructor usually passes in error information
class MyException extends Exception{
    
    
    public MyException(){
    
    
        
    }
    public MyException(String msg){
    
    
        super(msg);
    }
}

to sum up

  • Exceptions are only used to deal with abnormal situations, do not overuse exceptions to replace normal process control
  • For some predictable errors, programmers are fully capable of providing corresponding code to deal with, rather than throwing exceptions

E.g:

int a[]=new int[10];
for(int i=0;i<100;i++){
    
     
   try {
    
    
       System.out.println(a[i]);
   }catch (IndexOutOfBoundsException e){
    
    
       e.printStackTrace();
   }
}
  • This situation is foreseeable by programmers, and they are fully capable of using code to avoid such errors,
    instead of blindly throwing exceptions and then solving them.

  • This throwing exception is simple, but after the Java runtime catches the exception, it must enter the catch block.
    This will reduce the efficiency of the operation.

  • The original intention of the exception handling mechanism is to separate the handling code of unexpected exceptions from the normal business logic handling code, and
    never use exception handling to replace normal business logic judgments.

Guess you like

Origin blog.csdn.net/m0_47256162/article/details/111199862