Surpass Day20 – Java Exceptions

Table of contents

1. Compile-time exceptions and runtime exceptions​​​

1.1 Basic Concepts

1.2 The difference between the two

1.3 Handling exceptions

2. In-depth try…catch exception

2.1 Format of try…catch

2.2 About try…catch

2.3 New Features of JDK

2.4. How to choose between reporting and capturing

3. getMessage() method and printStackTrace() method

4. finally clause

5. The difference between final, finally and finalize

5.1 final

5.2 finally

5.3 finalize()

6. Custom exception

6.1 Steps for customizing exceptions

6.2 Improvement of stack memory program

7. The methods overridden by subclasses can only throw compilation exceptions less/smaller than more

1. Compile-time exceptions and runtime exceptions​​​

1.1 Basic Concepts

Both compile- , and compile-time exceptions do not occur ;

Compile-time exceptions must be pre-processed in the compilation (writing) phase, if the compiler errors are not processed;

All exceptions occur in the runtime phase, because only the program runtime phase can new objects. The occurrence of an exception is the new exception object

1.2 The difference between the two

Compile-time exceptions (checked exceptions, controlled exceptions) have a high probability of occurrence and need to be preprocessed before running;

The probability of runtime exceptions (unchecked exceptions, uncontrolled exceptions) is low, and no preprocessing is required before running;

1.3 Handling exceptions

1) In the position of the method declaration, use the throws keyword; [throw it to the upper level, whoever calls me, I will throw it to whoever; there are also two ways to throw it to the upper level]

After the exception occurs in java, if it keeps throwing up, it is finally thrown to the main method, and the main method continues to throw up and throws it to the caller JVM, and the JVM terminates the execution of the program

2) Use the try..cathch statement to catch exceptions; [No one knows what happened, because I caught it]

public class Sttt{
    public static void main(String[] args) {System.out 
        .println ( 100 / 0 );
 //At this point in the program execution, an ArithmeticException exception occurs, an ArithmeticException exception object is created at the bottom layer, and then thrown to the main method. The main method cannot be processed in the end, and the exception is thrown to the JVM, JVM Finally terminated the execution of the program 
        System. out .println( "helloworld" );
    }
}
//ArithmeticException inherits from RuntimeException, which is a runtime exception and does not need to be pre-processed when writing programs

public  class  Sttt {
     public  static  void  main (String[] args) throws ClassNotFoundException //Processing method 1 { 
        doSome () ; //Because there is throws ClassNotFoundException at the declaration position of doSome method (), so this exception should be handled when calling Perform preprocessing, if not processed, the compiler will report an error
    
        //Alt + Enter to generate
        
        try {
            doSome();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } //Processing method 2
    }
}
public  static  void  doSome ()  throws ClassNotFoundException {
 //ClassNotFoundException class does not find an exception, the parent class is Exception, so it is a compile-time exception 
}

3) When an exception is thrown, the parent object of the exception can be thrown

Multiple exceptions can be written after throws and separated by commas;

It is generally not recommended to use throws on the main method, because if this exception does occur, it will be thrown to the JVM, and the JVM can only terminate

The function of the exception handling mechanism is to improve the robustness of the program and ensure that the program can be executed even if there is an exception. Therefore, it is recommended to use try…catch to catch the exception in the main method. main don’t continue to toss

Note: As long as the exception is not caught, the subsequent code of this method will not be executed by the method of reporting. In addition, it should be noted that if an exception occurs in a line of the try block, the code after the change will not be executed, and the code following the try catch will still be executed.

2. In-depth try…catch exception

2.1 Format of try…catch

try {
     //try try
    m1();
} catch (FileNotFoudException e){
     //catch is the branch taken after catching the exception System.out 
    .println ( "The file does not exist, the path may be wrong, or the file may be deleted" );
}

2.2 About try…catch

  1. The type in parentheses after catch can be the specific exception type or the parent type of the exception type

  2. Multiple catches can be written to facilitate program debugging. When multiple catches are written from top to bottom, the order from small to large must be followed.

2.3 New Features of JDK

try{

}catch(FileNotFoundException|ArithmeticException|NullPointerException e){
​
}

2.4. How to choose between reporting and capturing

If you want the caller to handle it, select throws to report

3. getMessage() method and printStackTrace() method

public  class  Sttt {
     public  static  void  main ( String[] args ) {
         //In order to test two methods, the new exception object, but no exception object is thrown, JVM thinks it is a normal java object 
        NullPointerException e = new NullPointerException( "Null Pointer Exception!" );
         //Get a brief description of the exception: this information is actually the String parameter in the constructor
        String msg = e.getMessage();
        System.out.println(msg);
        e.printStackTrace(); //Print exception information. When java background prints exception stack information, it is printed by asynchronous thread.
    }
}

4. finally clause

1) The code in the finally clause is executed last and will definitely be executed, even if the code in the try statement block has an exception,

2) The finally clause must appear together with try and cannot be written alone;

3) The finally statement is usually used to complete the release/close of resources, because the code in the finally statement block is more secure, even if the code in the try statement block is abnormal, the code in the finally will work normally.

4) Even if the try statement block has return , finally will be executed, only when System.exit(0) exits the JVM , finally will not be executed

public class Sttt{
    public static void main(String[] args) {
        FileInputStream fis = null ; //The declaration position is placed outside try, so that try can be used in finally
         {
            FileInputStream fis = new FileInputStream( "D:\\java\javase" );
                     //Start reading the file 
                    String s = null ;
                     //Null pointer exception here
                    s.toString();
                    //The stream needs to be closed when it is used up, because the stream occupies resources 
                    //Even if the above program fails, the stream must be related 
                    //It may not be closed here 
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }catch (NullPointerException e){
            e.printStackTrace();
        } finally {
             //The closing of the stream is safer here 
            //The code in finally will be executed 
            //Even if an exception occurs in try 
            if (fis != null ) //Avoid null pointer exception 
                try {
                     //close () method has an exception, use the capture method
                    fis.close();
                } catch(IOException e){
                    e.printStackTrace();
                }
        }
    }
}

5) Interview questions

The syntax rules of java:

The code in the method body must be executed line by line in a top-down order (eternal syntax)

Once the return statement is executed, the entire method must end

public class Sttt{
    public static void main(String[] args) {
​
        System.out.println (m()); // The result is 100
    }
    public static int m() {
         int i= 100 ;
         try {
             //This line of code appears below int i = 100;, so the final result must be to return 100 //The 
            return statement must also be guaranteed to be executed last. Once executed, the entire method ends and
             returns i;
  //This can be understood as the top-down i has been passed into the return but has not been executed, so no matter how the value of i is changed before the return, the return i will not change 
        } finally {
            i++;
        }
    }
}

decompiled code

public static int m{
    int i = 100;
    int j = i;
    i++;
    return j;
}

5. The difference between final, finally and finalize

5.1 final

final is a keyword. means final, immutable

try{
​
}finally{

}

5.2 finally

finally is also a keyword. Used in conjunction with try, used in the exception handling mechanism

The code in the finally block will be executed

public  class  Sttt {
     public  static  void  main (String[] args)  {
         //A new exception object (not thrown manually) 
        MyException e = new MyException( "Username cannot be empty" );
         //Print exception information
         e.printStackTrace();
        //Get exception brief description information
        String msg = e.getMessage();
        System.out.println(msg);
    }
}
​
public class MyException extends Exception{
    public MyException(){

    }
    public MyException(String s){
        super(s);
    }
}

5.3 finalize()

finalize() is a method of the Object class, which appears as a method name, so finalize is an identifier

The finalize() method is the responsibility of the JVM’s GC garbage collector to call

6. Custom exception

6.1 Steps for customizing exceptions

Step 1: Write a class that inherits Exception or RubtimeException

Step 2: Write two constructors, one with no parameters and one with parameters

Note: throw is used when throwing exceptions manually , throws means reporting exception information to the caller

public  class  Text { 
    public  static  void  main (String[] args)  {
         //Create a stack object with an initial capacity of 10 Stacks 
        = new Stack();
        s.push("12345ty");
        s.push(new Object());
        s.push(new Object());
        s.push(new Object());
        s.push(new Object());
        s.pop();
        s.pop();
        s.pop();
        s.pop();
        s.pop();
        s.pop();
        //You can use for loop to push and pop the stack
    }
}
class  Stack { 
    //Array to store any reference type data 
    private Object[] elements;
     //Constructor with parameters 
    public  Stack (Object[] elements)  {
         this .elements = elements;
    }
    //No-parameter constructor 
    public  Stack ()  {
         //Dynamic initialization of one-dimensional array 
        //The default initialized capacity is 10 
        this .elements = new Object[ 10 ];
    }
    //stack frame (always pointing to the top element of the stack) 
    private  int index= -1 ;

6.2 Improvement of stack memory program

// Compress method 
public  void  push (Object obj)  throws MystackQperationException {
    
    
                      // point! ! ! ! ! ! ! ! ! ! ! ! ! 
    if ( this .index >= this .elements.length- 1 ){
         throw  new MystackQperationException( "The stack memory is full, and the stack failed to push" );
         //Don't try...catch, you must catch new yourself Throw to caller 
    } // Improvements are made here 
                      // Important! ! ! ! ! ! ! ! ! ! ! ! !
    
    
    index++;
    elements[index] = obj;
    System.out.println(obj + "element, push the stack successfully, the stack frame points to " + index);
}
​
public  void  pop ()  throws MystackQperationException {
    
    
                    // point! ! ! ! ! ! ! ! ! ! ! ! ! 
    if ( this .index <= - 1 ) {
         //System.out.println("The stack memory is empty, the stack popping failed"); 
        throw  new MystackQperationException( "The stack memory is empty, the stack popping failed" );  
    }
                    // point! ! ! ! ! ! ! ! ! ! ! ! !
    
    
    else 
        System.out.println(elements[index] + "element, popped the stack successfully, the stack frame points to" + --index);
}
//Custom stack operation exception 
public  class  MystackQperationException {
     public MystackQperationException{
        
    }
    public MystackQperationException(String s){
        super(s);
    }
}

//get method of static instance variable 
public Object[] getElements () {
    return elements;
}
//set method of static instance variable 
public  void  setElements ( Object[] elements ) {
     this .elements = elements;
}
//get method of instance variable stack frame 
public  int  getIndex () {
    return index;
}
//set method of instance variable stack frame 
public  void  setIndex ( int index ) {
     this .index = index;
}
}

class Animal{
    public void doSome(){

    }
    public void doOther() throws Exception{

    }
}
class  Cat  extends  Animal {
     public  void  doSome ()  throws Exception {
         //Compile error
    }
    public  void  doOther ()  throws Exception {
         //compile normally
    }
    public  void  doOther () {
         //compiles normally
    }
    public  void  doOther ()  throws NullPointerException {
         //Compile normally
    }
    public  void  doSome ()  throws RuntimeException {
         //Running compiled subclasses can throw more normally, but compile exceptions can't
    }
}

7. The methods overridden by [subclasses] can only throw compilation exceptions less/smaller than more

class Animal{
    public void doSome(){

    }
    public void doOther() throws Exception{

    }
}
class  Cat  extends  Animal {
     public  void  doSome ()  throws Exception {
         //Compile error
    }
    public  void  doOther ()  throws Exception {
         //compile normally
    }
    public  void  doOther () {
         //compiles normally
    }
    public  void  doOther ()  throws NullPointerException {
         //Compile normally
    }
    public  void  doSome ()  throws RuntimeException {
         //Running compiled subclasses can throw more normally, but compile exceptions can't
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *