[135 days] Shang Xue Gao Qi Java300 video highlights notes (74-76)

Keywords: Java Database

Set 74-75: exception mechanism, trycatch finallyreturn execution order, catch exception, declare exception throw, handle exception in method rewriting, throw exception manually

Exception handling method 1: catch exceptions

try

  1. The try statement specifies a piece of code that is the scope of a single capture and processing. In the execution process, when any statement produces an exception, the later code in the paragraph is skipped. One or more types of exception objects may be generated and thrown in the code, and the catch statement behind it will deal with these exceptions separately.

  2. A try statement must have at least one catch statement block or a final statement block. [Only try and finally may not be possible]

  3. When the execution of exception handling code ends, it does not go back to the try statement to execute the code that has not yet been executed.

catch

  1. Each try statement block can be accompanied by one or more catch statements to handle different types of exception objects that may be generated.

  2. Common methods:

    1. toString (): Shows the class name of the exception and the cause of the exception.

    2. getMessage(): Shows only the cause of the exception, but not the class name.

    3. printStackTrace(): Used to track the contents of the stack when an exception occurs. [Most commonly used]

    These methods all inherit from the Throwable class

  3. Catch catches exceptions in the order of capture:

    1. If there is an inheritance relationship between exception classes, attention should be paid to the sequencing. The more top-level classes are, the more they are placed below. Otherwise, the redundant catch es will be omitted directly.  

finally

Some statements, whether or not an exception has occurred, must be executed, so you can put such statements in the final statement block.
Usually, open resources of program blocks are closed in final, such as file stream, release database connection, etc.

package com.test074;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Test074 {
    public static void main(String[] args){
        FileReader reader = null;
        File a = new File("/Users/wangtao/Desktop/a.txt");
            
        try{
            a.createNewFile();
            reader = new FileReader("/Users/wangtao/Desktop/a.txt");
            char temp = (char)reader.read();
            System.out.println("Read out"+temp);
        } catch(FileNotFoundException e){
            System.out.println("The file was not found.");
        } catch(IOException e){
            e.printStackTrace();
            System.out.println("File Reading Error");
        } finally {
            System.out.println("Whether there is an exception or not, it will be executed.");
            try {
                reader.close();//This is a method for closing objects
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

try, catch, final, return execution order

  1. Execute try,catch, and assign the return value

  2. Execute final

  3. return

package com.test074;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test074_1 {
    public static void main(String[] args){
        String str = new Test074_1().openFile();
        System.out.println(str);
    }
    
    String openFile(){
        try{
            System.out.println("aaa");
            FileInputStream fis = new FileInputStream("/Users/wangtao/Desktop/a.txt");
            int a = fis.read();
            System.out.println("bbb");
            return "step1";
        } catch(FileNotFoundException e) {
            System.out.println("catch");
            e.printStackTrace();
            return "step2";//Go to finally and come back here.
        } catch(IOException e){
            e.printStackTrace();
            return "step3";
        } finally {
            System.out.println("finally!!!");
            //return "FFF";//Do not use return in final
        }
        
    }
}

The second way to deal with exceptions is to declare exceptions: throws clause

  1. When Checked Exception is generated, it does not necessarily need to be handled immediately, and the exception Throws can be sent out again.

  2. In this method, try-chatch-final is used to handle exceptions. In some cases, the current method does not need to handle the exception that occurs, but passes it up to the method that calls it.

  3. If an exception may occur in a method, but it is not clear how to handle the exception, the exception that the method may throw should be declared at the beginning of the method according to the exception specification.

  4. If a method throws multiple checked exceptions, it must list all exceptions at the beginning of the method separated by commas.

  5. The principle of declaring exceptions in method rewriting is that the scope of exceptions declared by subclasses should not exceed that declared by parent classes. It contains the following meanings:

    1. The parent class does not declare exceptions, nor can the child class.

    2. The parent or upper class of an exception class cannot be thrown by the original method.

    3. The number of exception types thrown cannot be more than the number thrown by the original method.

package com.test075;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;

/**
 * @author wangtao
 *    Test subclass override parent method
 *    1. Exceptions thrown by subclasses cannot be superclasses of parent classes, nor can they exceed the scope of parent classes.
 *    2. Subclasses cannot throw more types of exceptions than parent classes
 *    3. The parent class does not throw an exception, and the child class does not.
 *    
 */
public class Test075_1 {
    
    
    
    public static void main(String[] args){
        
    }
    
    
    
    class A {
        public void method() throws IOException{
            
        }
    }
    
    class B extends A {
        public void method() throws FileNotFoundException{//Exceptions thrown by subclasses do not exceed the parent range
            
        }
    }
    
    class C extends A {
        public void method(){//Subclasses do not throw exceptions
            
        }
    }
    
    class D extends A {
        public void method() throws IOException,ParseException{//Subclasses throw more types of exceptions than parent classes and report errors
            
        }
    }
    
    class E extends A {
        public void method() throws IOException,FileNotFoundException{//Subclasses throw more exception scopes than their parents, but they do not exceed their parents'scopes.
            
        }
    }
    
    class F extends A {
        public void method() throws IOException,ArithmeticException{//Ditto
            
        }
    }
}

The third way to deal with exceptions is to throw exceptions manually

  1. Java exception class objects are automatically generated and thrown by the system when an exception occurs during program execution, and can also be created and thrown manually as needed.

  2. Before capturing an exception, a piece of code must be thrown as an exception object. This process can be done by hand or by JRE, but all they call are throw clauses.

  3. For an existing exception class, the process of throwing the exception object is as follows:

    1. Find a suitable exception class.

    2. Create an object of this class.

    3. Throw an object.

package com.test075;

import java.io.File;
import java.io.FileNotFoundException;

public class Test075_2 {
    public static void main(String[] args){
        File f = new File("/Users/wangtao/Desktop/aaa.txx");
        if(!f.exists()){
            try {
                throw new FileNotFoundException("File can`t be found!");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Set 76: exception mechanism, custom exception, exception summary

Custom exceptions

  1. In a program, you may encounter the problem that any standard exception class is not fully described. In this case, you can create your own exception class [just derive a subclass from Exception class or its subclass].

  2. Traditionally, classes defined should contain two constructors: the default constructor and the constructor with detailed information.

package com.test076;

/**
 * @author wangtao
 * Test custom exceptions
 */
public class Test076 {
    public static void main(String[] args){
        try {
            new TestMyException().test();
        } catch (MyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class MyException extends Exception {
    public MyException(){
        
    }
    
    public MyException(String message){
        super(message);
    }
}

class TestMyException{
    void test() throws MyException {
        
    }
}

Suggestions on Using Exception Mechanisms

  1. To avoid using exception handling instead of error handling, this will reduce the clarity of the program and inefficiency.

  2. Handling exceptions is not a substitute for simple testing -- use exception mechanisms only in exceptional situations

  3. Don't do small-grained exception handling -- wrap the entire task in a Try block.

  4. Exceptions are often handled at a high level (understand first! After doing the project will say! )

summary

  1. A graph

  2. Five keywords (try,catch,finally,throws,throw)

  3. First catch the small ones, then the big ones.

  4. The relationship between exceptions and rewrites

  5. Custom exception

Posted by Clinger on Thu, 20 Jun 2019 14:15:40 -0700