2019-08-17 (Java generic classes and exception handling)

1. Knowledge Points:

1. Generic classes
2. exception handling

2. Use of knowledge points:

1. In practice, there are not many places where generics are used, so generic classes are only introduced here.

General format of generic classes:

// Generic identifier: Any identifier number can be written to identify the type of the specified generic type.
Class class name < generic identifier >{
// Generic variables
  private generic identifier a; 
// Generic Method
 public return value function name (parameter type parameter name, generic identifier parameter name){
        // Function Body
    }  
}

Example:

public class MyClass {
    public static void main(String[] args){
        GenericTest<Integer> genericTest = new GenericTest<>();
        genericTest.test(10,10);
    }
}
class GenericTest<T>{
    int age;
    T a1;
    T a2;
    public void test(T a1, T a2){
        this.a1 = a1;
        this.a2 = a2;
        System.out.println(a1);
        System.out.println(a1.equals(a2));
    }
}
2. Exception handling:
  • The framework of exception classes and their subclasses:


    image.png
  • Definition of exceptions: Exceptions are errors in the process of program running. They are described by classes in Java and expressed by objects. Java divides it into Error and Exception, Error is an error that the program can not handle, Exception is an error that the program can handle. Exception handling is for the robustness of the program.
  • Exception handling keywords:
    1. The try statement: Specifies a piece of code in braces {}, which may discard one or more exceptions.
    2. The catch statement: The parameters of the catch statement are similar to the declaration of the method, including an exception type and an exception object. The exception type indicates the exception type that the catch statement handles. The exception object is generated and captured by the runtime system in the block of code specified by try. The curly brackets contain the processing of the object, in which the method of the object can be invoked.
    3. Final statement: In the code qualified by try, when an exception is discarded, subsequent code will not be executed. A block of code can be specified by the final statement. In any case, the code specified by finally is executed, providing a unified exit. Usually in the final statement, resources can be cleaned up, such as closing, opening files, etc.
    4. Throws statement: throws always appear in a function header to indicate various exceptions that the member function may throw.
    5. Throw statement: throw always appears in the body of a function to throw an exception. The program terminates immediately after the throw statement, and the following statement does not execute.
  • Exception chains: (common methods in Throwable classes)
  1. getCause(): Returns the cause of the exception thrown. If cause does not exist or is unknown, return null.
  2. getMessage(): Returns message information for exceptions.
  3. printStackTrace(): The stack trace of the object is output to the error output stream, which is the exception chain of the field System.err, as its name implies, to the exception.
    The reason for this happens is that the abnormal information of the bottom layer is transmitted to the upper layer one by one, which is thrown out layer by layer.
3. Practical application of exception handling:
  • Conventional model:
        FileReader reader = null;
        try {
            System.out.println("Hello");
            reader = new FileReader("re");
            
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            try{
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
  • After try, parentheses are added:
        //Only objects that can be closed can be added in parentheses of try
        //Objects that implement the Closeable interface, and if an exception occurs, the system closes the resource itself
        try (FileReader reader1 = new FileReader("rewrwr")){
            //Use Objects
        }catch (IOException e){
            e.printStackTrace();
        }
  • Write a method that throws an exception in the method:
        try {
            TException.test();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }

        try {
            TException.test3();
        }catch (ykException e){
            System.out.println(e.getMessage());
        }
//Custom class:
class TException{
    public static void test() throws  FileNotFoundException,NullPointerException{
        FileReader reader = new FileReader("fsf");

    }
    //Three:
    public static void test2()throws IllegalAccessException {
        if (2 > 1){
            throw new IllegalAccessException();
        }
    }
}
  • Custom exceptions:
        try {
            TException.test3();
        }catch (ykException e){
            System.out.println(e.getMessage());
        }
class TException{
    public static void test3() throws ykException {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StackTraceElement e = stackTrace[2];
        String detail = e.getFileName()+"->"+e.getMethodName()+"->"+e.getLineNumber();
        throw new ykException( "My own anomalous class: inaction"+detail);
    }
}
//Custom exception
class ykException extends java.lang.Exception{
    //Providing a tragic-free construction method
    public ykException (){}
    //Providing a tragic construction method
    public ykException(String desc){
        super(desc);
    }
}
4. Part of the summary:
  • Exception handling format:
try{
//Code to execute
//Once an exception occurs, the system automatically creates an exception class for us and outputs it
 }catch(NullPointerException  e){
//If you need to handle exceptions yourself, catch
 }catch(IOExcepton e){

 //If there are multiple exceptions, the catch order is from small to large
}catch(Exception e){

}finally{
 //Resource Recovery: Network Connection Database Connection File Stream I/O Stream
// No matter what, finally will be executed.
}
  • Starting with exceptions, the later code will not execute, instead, it will execute catch code, so don't catch too many exceptions.
  • The second exception handling method: throws are used and handed over to external processing

Keywords: Java network Database

Added by phpSensei on Sat, 17 Aug 2019 15:14:12 +0300