• Method creates an exception object for the JVM to handle. This exception object contains the exception name, the exception description, and the state of the application when the exception occurs. The process of creating an exception object and presenting it to the JVM is called throwing an exception. There will be a series of method calls, and the ordered list of method calls is called the call stack
  • The JVM follows the call stack to see if there is any code that can handle an exception, and when the JVM finds code that can handle an exception, it passes the exception to it. If the JVM does not find a block of code to handle the exception, the JVM passes the exception to the default exception handler, which prints out the exception message

1. Classification and inheritance of exceptions


  • Throwable is the superclass for all errors and exceptions in the Java language. Throwable contains two subclasses: Error and Exception.
  • Error is not handled in the program. These errors are unchecked exceptions, non-code errors. Therefore, the program should not handle such errors when they occur. By convention, we should not implement any new Error subclasses either
  • An Exception is an Exception that the program itself can catch and handle. Exceptions fall into two further categories: runtimeExceptions and compile-time exceptions.

Analysis of several common exception classes

  • RuntimeException(unchecked exception) is a superclass that Java throws exceptions while the virtual machine is running. Any subclasses of RuntimeException thrown during method execution need not be declared in the throws throws clause because it is uncheckedExcepiton. There are five common runtimeExceptions
    • Java. Lang. ArithmeticException (arithmetic exception)
    • Java. Lang. ClassCastException (type conversion)
    • Java. Lang. IllegalArgumentException (illegal parameters)
    • Java. Lang. IndexOutOfBoundsException (array subscript crossing the line)
    • Java. Lang. NullPointerException (null pointer exception)
  • Exception definition: Exceptions in Exception other than RuntimeException and its subclasses. Features: The Java compiler requires that your program catch or declare to throw this exception
    • Java.io.IOException(IO flow exception)
    • Java. Lang. ClassNotFoundException (there is no specified class exception)
    • Java. Lang. NoSuchFieldException didn’t find the specified field (abnormal)
    • Java. Lang. NoSuchMetodException (haven’t found a way to specify exceptions)
    • Java. Lang. IllegalAccessException illegal access (abnormal)
    • Java. Lang. InterruptedException (interrupt)

3 Java exception keyword

The keyword Function description
try{ } The code that might throw an exception is placed inside the try block, and when an exception occurs inside the try block, the exception is thrown
catch(e) Catch exception E; Catch is used to catch exceptions that occur in a try block. Multiple catches can be declared, and multiple exceptions can be caught within a catch
finally The finally block is always executed. Mainly used to reclaim resources (such as database connections, TCP connections, and file streams) that are opened in the try block
throw To throw an exception
throws Declare exceptions that the method may throw
  • Note: Before executing a try, catch, or return or throw statement elsewhere, you need to execute the code in finally. If there is a return or throw statement in finally, the method terminates after executing the return or throw statement in finally
public int hello(String fileName) throws RuntimeException{

 int a = 10;

    try{

        File file = new File(fileName);

        FileInputStream in = new FileInputStream(file);

        return a; // Returns the value 10

    }catch (FileNotFoundException e){

        System.out.println("error occurred");

    }catch (ArithmeticException | IndexOutOfBoundsException e){

        System.out.println("whatever");

    } finally{

        System.out.println("finally");

        a = 20// Finally change a, and do not change the result of return 10 in try

        // return a; // If returned here, the return value is equal to 20

    }

    return -1;

}

Copy the code

4 Precautions for handling exceptions during development

  • Throws an explicit exception and documents the exception
    • If a method has exceptions that need to be handled externally, declare throws specific exceptions for the caller to handle
    • You also need to comment when you declare a method to throw an exception. The goal is to give the caller as much information as possible to handle exceptions
  • Use identifying messages to define exceptions: Easy to pinpoint problems
  • The most specific subclass exceptions are caught first
    • If you catch an Exception superclass first, such as catch(Exception e), the code that catches the catch(RunTimeExcption e) will not be executed
  • Do not capture the Throwable class
    • Because Throwable is an Error and Exception superclass, Error is a JVM, system-level Error and should not be caught and handled generally
  • Do not handle exceptions after they are captured: If the root cause of abnormal errors cannot be located, you are advised to at least generate logs
  • Do not record and throw exceptions: If multiple logs are generated for the same exception, it is difficult to find the root cause of the error
  • Do not discard the original exception when wrapping novelty
    • If the original exception is discarded, the stack trace and messages for the original exception are lost, making it difficult to analyze exception events
  • Note: Exceptions affect performance
    • The performance cost of exception handling is very high, creating an exception is very slow, and throwing an exception takes another 1 to 5ms. Try not to use exceptions to control your code logic

5 Exceptions and AutoCloseable(1.7-JDK syntax sugar)

  • In catch exception handling, we often open resources (TCP links, file streams) in a try. In case an exception occurs and the resource is not closed, all resource closure needs to be executed in finally code
  • Is there a convenient way? After the 1.7 JDK, Java provided try–with–resource syntax sugar. Resource objects need to implement AutoCloseable. When you open a resource in a try(), the resource is automatically closed
  • The InputStream subclasses all inherit AutoCloseable, which automatically closes an example of the use of the resource class FileInputStream
File file = new File("./text.txt");

try (FileInputStream in =new FileInputStream(file)){

.// Data manipulation

catch (Exception e) {

    log.error(e.getMessage(), e);

.

}

Copy the code

6 Throw and throws

  • The throw keyword is used inside a method and can only be used to throw one exception. It can be used to throw an exception in a method or block of code
  • Throws a list of exceptions that the method may throw. A method identifies a list of exceptions that may be thrown with throws. The method calling the method must contain code that can handle exceptions; otherwise, the method signature must declare the corresponding exception with the throws keyword

7 guava’s Throwables class

  • If you need to invoke chain operations on exceptions, you can use the Throwables utility class.
// Get the exception chain of the throwable as a list

public static List<Throwable> getCausalChain(Throwable throwable)

// return the lowest level exception

public static Throwable getRootCause(Throwable throwable)

// Convert checked exceptions to runtime exceptions

// Get the description output of the exception call chain (each line)

public static String getStackTraceAsString(Throwable throwable)

If the exception is similar to declaredType, throw an exception and pass throwable

public static <X extends Throwable> void propagateIfInstanceOf(

      @Nullable Throwable throwable, Class<X> declaredType)
 throws X

// Throwable is passed if and only if it is a RuntimeException and Error, or an instance of X

void propagateIfPossible(Throwable, Class<X extends Throwable>) throws X

// Convert Throwable to RuntimeException. This method is not recommended

public static RuntimeException propagate(Throwable throwable)

Copy the code
  • The instance
public static void main(String args[]) throws FileNotFoundException {

    try {

        File file = new File("./text.txt");

        FileInputStream inputStream = new FileInputStream(file);

    } catch (Exception e) {

     // Get the exception call stack information and print it (or save it elsewhere)

        String errorMsg = Throwables.getStackTraceAsString(e);

        System.out.println(errorMsg);

        // If e is FileNotFoundException, throw it

        Throwables.propagateIfInstanceOf(e, FileNotFoundException.class);

        // Other throwables are thrown as RuntimeException classes

        throw Throwables.propagate(e);

    }

}

Copy the code

Pay attention to the public number, communicate together


Refer to the article

  • Java exception interview question
  • Guava’s exception tool class –Throwables