Java learning notes -- abnormal knowledge notes

Posted by pages on Wed, 09 Feb 2022 23:02:15 +0100

Combine learning and rookie notes ~ attach the website about exceptions in the rookie tutorial
https://www.runoob.com/java/java-exceptions.html

Why should we handle exceptions? When an exception is encountered during the execution of the program (the exception is usually difficult to solve, such as the disconnection exception caused by unplugging the network cable), the execution will be directly suspended, which is very bad for the user experience. In order to ensure the normal and smooth execution of the subsequent program, we introduce the object-oriented exception mechanism.
In case of an error, the system throws an exception. We catch the exception, handle the output error prompt, and continue to execute other parts of the program

Classification of anomalies

  • Detectability exception: the detectability exception is verified by the compiler. For any method that claims to throw an exception, the compiler will enforce the processing or declaration rules. If this exception is not caught, the compiler will not pass and compilation is not allowed. The compiler should check this kind of exception. On the one hand, the purpose of checking is because the occurrence of this kind of exception is inevitable. On the other hand, it is to let developers solve this kind of exception. Therefore, it is called the exception that must be handled (try... catch / throws).
    If such exceptions are not handled, the compiler in the integrated development environment will generally give an error prompt.

For example: FileInputStream fis=new FileInputStream("./src/io/BRDemo.java");
The statement must try... catch or throw to avoid IOException

  • Non detectable exception / runtime exception: in short, they are all errors that can be corrected by logic, which can be called bug s. Similar to null pointer exceptions, we can avoid such exceptions through if branch judgment, or those very common statements.
    If such exceptions are not handled, the compiler in the integrated development environment will not give an error prompt.

For example: null pointer exception NullPointerException, even if we have it, the system will not prompt us to catch it. We can modify the program to avoid it.
Only the RuntimeException class belongs to the non detection exception, because the exception caused by the ordinary JVM during operation may occur at any time. This kind of exception is generally caused by a specific operation. However, these operations occur frequently in java applications because they are not limited by compiler checking and processing or declaration rules

Common subtypes of RuntimeException

  • **Error: * * the error is not an exception, but a problem out of the control of the programmer. Errors are usually ignored in code. For example, when the stack overflows, an error occurs, and they cannot be checked during compilation.

Hierarchy of Exception

All exception classes are from Java A subclass inherited by the lang.exception class.
The Exception class is a subclass of the Throwable class. In addition to the Exception class, Throwable also has a subclass Error.
Exception classes have two main subclasses: IOException class and RuntimeException class.

Java programs usually do not catch errors. Errors usually occur in the case of serious failures, which are outside the scope of Java program processing.
Error is used to indicate an error in the runtime environment.
For example, JVM memory overflow. Generally, programs do not recover from errors.

catch exception: try - catch - finally

Basic grammar
try{
   Code snippets with possible exceptions
}catch(XXXException e){
   When try Appear in XXXException Solution after
}finally{
   whether try Whether there is an exception in, finally Code in is always executed
   It can store the closing and aftermath statements such as cleaning type
   such as IO After operation close()Call.
}
//give an example:
public class Demo {
   public static void main(String[] args) {
       System.out.println("The program begins");
       try {
           String str = null;
           System.out.println(str.length());
           return;//finally must be executed before the method actually returns
       }catch(Exception e){
           System.out.println("Error !");
       }finally {
           System.out.println("finally The code in is executed!");
       }
       System.out.println("The program is over");
   }
}
Extension:
  • Multiple capture blocks: a try code block is followed by multiple catch code blocks.

    Note: multiple catches must be subtype exceptions at the top and supertype / large range exceptions at the bottom

try{

}catch(){

}catch(){

}catch(){

}...
  • Exceptions can be captured in combination. This method can be used when different exception handling methods are the same.
try{
	  Statement block to check
}catch(NullPointerException|StringIndexOutOfBoundsException e){
     System.out.println("Processing of null pointer or subscript out of bounds occurred!");
}catch(Exception e){
     System.out.println("There was a mistake anyway!");
}
be careful:
  • The try statement block cannot exist independently. It must be followed by catch or finally.

  • No code can be added between try, catch and finally blocks.

Exception handling in IO:

Let's look at the following code first

public class FinallyDemo2 {
   public static void main(String[] args) {
       FileOutputStream fos = null;
       try {
           fos = new FileOutputStream("fos.dat");
           fos.write(1);
       }catch(IOException e){
           System.out.println("Something went wrong! Solved here!");
       }finally{
           try {
               if(fos!=null) { //Prevent null pointer exceptions
                   fos.close();
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }
}

We can find it very troublesome, because the in finally also needs to be captured. JDK1.7 introduces the automatic shutdown feature, which simplifies the exception handling mechanism in the source code in IO applications: autoclosable

Note that this feature is still recognized by the compiler, not the virtual machine. It's just that the compiler helped us do the above troublesome things

AutoCloseable is an interface, and the class implementing the interface will have the feature of automatic shutdown.
How can we achieve it?

public class AutoCloseableDemo {
    public static void main(String[] args) {
        //There is a bracket () after try, which contains relevant statements
        try(
                /*
                    Only classes that implement the AutoCloseable interface can be defined and initialized here.
                    At compile time, the compiler calls the variable defined here in finally and closes it in close.
                    Finally, the compiler will change the current code to look like FinallyDemo2.
                 */
                FileOutputStream fos = new FileOutputStream("fos.dat");
        ){
            String line = "hello";
            fos.write(1);
        }catch(IOException e){
            System.out.println("Error ");
        }
    }
}

throw and throws

throw

Introduction: how Java handles exceptions. If an exception occurs in Java code, the jvm will throw an exception object, resulting in program code interruption. At this time, the jvm is doing: create an exception object and then throw it: This is what the jvm automatically helps us do, as follows:

int i=1; int j=0; int res=0;
res=i/j; //If a divide by zero error occurs, the system will interrupt and throw an exception automatically when it runs here

But! For some special application requirements, such as user-defined exceptions and application specific exceptions, you need to actively throw them with the help of throw statements, for example:

public void setAge(){
    int age = 0 ; 
	age = -100 ; 
	if(age<0 ) 
 	{ 
   		throw new Exception("IllegalAgeException");//Create exception object 
	}  
	System.out.println(age);
}

Here, when calling setAge method, the system will know that there may be exceptions and need to be handled. He asked us to try... catch or throw

throws

When the method / statement throws a method, we need to deal with it. If you don't want to try... catch this exception in person. We can throw an exception class name after the method declaration. In this way, when others call the method through the class, they will know that I need to handle this exception (of course, I can continue to throw and know the main method)

Syntax note: throws indicates that an exception is thrown and handled by the caller of the method; It can be separated from multiple exception class names by commas; Throws indicates a possibility of exceptions that do not necessarily occur

give an example:

void fun()throws  IOException,SQLException { 
 	xxx;
} //Indicates that IO and SQL exceptions may occur when the fun() method is executed, and the fun method is not handled internally

main(){//The two exceptions need to be handled when calling the main method
    try{
        fun();
	}catch(IOException){
        
    }catch(SQLException){
        
    }
}
Summary

Throw: is used to throw a specific exception type. When used in a method body, it is followed by the exception object name. Only one exception object name can be thrown. Indicates that an exception is thrown, which is handled by the statement in the method body. Throw means that an exception is thrown, and execution of throw must throw some kind of exception.

throws: it is used to declare all the exceptions that may be generated by a method. Instead of doing any processing, it uploads the exceptions. I will throw them to whoever calls me. Used after the method declaration, followed by the exception class name. It can be separated from multiple exception class names with commas. throws indicates a possibility of exceptions. These exceptions do not necessarily occur.

throw rule when subclass overrides parent method

Explain with examples:
We make the parent class as follows:

public class ThrowsDemo {
    //The dosome method throws two exceptions
    public void dosome()throws IOException, AWTException {}
}

Subclass overrides the method of the parent class

  • The following can be written

    class SubClass extends ThrowsDemo{
        //Throw an equal exception
        public void dosome()throws IOException, AWTException {}
    
        //Only partial exceptions are allowed
        public void dosome()throws IOException{}
    
        //Allow no more exceptions to be thrown
        public void dosome(){}
    
        //Subtype exceptions that allow superclass methods to throw exceptions
        public void dosome()throws FileNotFoundException {}
    
    }
    
    
  • The following wording is not allowed

    class SubClass extends ThrowsDemo{
        
        //It is not allowed to throw additional exceptions (if the superclass method does not declare to throw or has no inheritance relationship with the exceptions thrown by the superclass declaration)
        public void dosome()throws SQLException {}
    
        //Superclass methods are not allowed to throw exceptions
        public void dosome()throws Exception {}
    }
    
    

Common Java exceptions - too long to write a separate article~

Topics: Java Back-end