Basic part: deep analysis of Java exception

Time:2020-10-23
  • Method, an exception object is created and handed to the JVM for processing. The exception object contains the name of the exception, the description of the exception, and the state of the application when the exception occurs. The process of creating an exception object and handing it to the JVM is called throwing an exception. There will be a series of method calls, the ordered list of which is called the call stack
  • The JVM will look up the call stack to see if there is any code that can handle the exception. When the JVM finds the code that can handle the exception, it will pass the exception to it. If the JVM does not find a code block that can handle the exception, the JVM passes the exception to the default exception handler, which prints the exception information

Classification and inheritance of anomalies

Basic part: deep analysis of Java exception

  • Throwable is a superclass of all errors and exceptions in the Java language. Throwable contains two subclasses: error and exception
  • Errors cannot be handled in the program. These errors are undetected exceptions and non code errors. Therefore, when such an error occurs, the program should not handle it. By convention, we should not implement any of the new error subclasses
  • Exception is an exception that can be caught and handled by the program itself. There are two types of exceptions: runtime exception and compile time exception

Analysis of two common exception classes

  • RuntimeException is a superclass in which Java throws an exception while the virtual machine is running. Any subclass of a runtimeException thrown during method execution does not need to be declared in the throws clause, because it is an uncheckedexception. Five common runtimeexceptions

    • java.lang.ArithmeticException (arithmetic exception)
    • java.lang.ClassCastException (type conversion exception)
    • java.lang.IllegalArgumentException (illegal parameter exception)
    • java.lang.IndexOutOfBoundsException (array subscript out of bounds exception)
    • java.lang.NullPointerException (null pointer exception)
  • Exception definition: exception in exception except runtimeException and its subclasses. Features: the java compiler requires the program to catch or declare to throw this exception

    • java.io.IOException (IO stream exception)
    • java.lang.ClassNotFoundException (the specified class exception was not found)
    • java.lang.NoSuchFieldException (the specified field exception was not found)
    • java.lang.NoSuchMetodException (the specified method exception was not found)
    • java.lang.IllegalAccessException (illegal access exception)
    • java.lang.InterruptedException (interrupt exception)

3 Java exception keyword

keyword Function description
try{ } The code that may throw an exception is placed in the try statement block. When an exception occurs in the try statement block, the exception is thrown
catch(e) Catch exception E; catch is used to catch the exception in the try statement block. Multiple catch can be declared, and multiple exceptions can be caught in the catch
finally Finally, blocks of statements are always executed. It is mainly used to recycle the resources opened in the try code block (such as database connection, TCP connection and file stream)
throw Used to throw an exception
throws Declare the exception that the method may throw
  • be careful:Before executing the return and throw statements of try, catch or other places, the code in finally needs to be executed. If there are return and throw statements in finally, the method ends after the return or throw statements in finally are executed
public int hello(String fileName) throws RuntimeException{

4. Attention points for exception handling in development process

  • Throw an explicit exception and document the exception

    • If there are exceptions in the method that need to be handled externally, please declare throws to throw specific exceptions for the convenience of the caller
    • When you declare that an exception is thrown on a method, you also need to comment on it. The purpose is to provide callers with as much information as possible to facilitate the handling of exceptions
  • Defining exceptions with identifying messages: convenient and accurate positioning
  • Catch the most specific subclass exception first

    • If you first catch an exception superclass, such as catch (exception E), then the code that catches catch (RuntimeException E) will not be executed
  • Do not capture throwable classes

    • Since throwable is a superclass of error and exception, and error is a JVM and system level error, it should not be captured and handled in general
  • Don’t leave exception handling after catching exception: unable to locate the root cause of the abnormal error. It is recommended to output the log at least
  • Do not record and throw exceptions: causes the same exception to output multiple identical logs, so it is not easy to find the root cause of the error
  • Do not discard the original exception when wrapping a new exception

    • If the original exception is discarded, the stack trace and the message of the original exception will be lost, which makes it difficult to analyze the exception event
  • Note: exceptions can affect performance

    • The performance cost of exception handling is very high, creating an exception is very slow, and throwing an exception will consume 1 ~ 5ms. Try not to use exceptions to control the logic of your code

5 exception and autocolosable (syntax sugar of 1.7-jdk)

  • In catching exception handling, we often open resources (TCP links, file streams) in try. In order to prevent the resource from being closed due to the exception, the closing of the resource needs to be executed in the finally code fast
  • Is there a convenient way? After 1.7 JDK, Java provides a try — with — resource syntax sugar. The resource object needs to implement autocolosable. If you open the resource in try(), the related resource will be automatically closed, and no longer need to be executed manually, whether it is normal exit or abnormal exit

Basic part: deep analysis of Java exception

  • The subclasses of InputStream inherit autoclosable, and automatically close the use example of resource class FileInputStream
File file = new File("./ text.txt "";

6 the difference between throw and throws

  • The throw keyword is used inside a method and can only be used to throw an exception. It can be used to throw an exception in a method or code block. Checked and non queried exceptions can be thrown
  • The throws keyword is used on a method declaration and can throw multiple exceptions to identify the list of exceptions that the method may throw. A method uses throws to identify the list of exceptions that may be thrown. The method calling the method must contain code that can handle the exception. Otherwise, the corresponding exception must be declared with the throws keyword in the method signature

7 guava Throwables class to understand

  • If you need to call chain operations on exceptions, you can use the Throwables tool class. The commonly used methods of Throwables are as follows:
//Get the throwable exception chain in the form of list
  • example
public static void main(String args[]) throws FileNotFoundException {

Welcome refers to the error in the text

Pay attention to official account and exchange with you.

Basic part: deep analysis of Java exception

Reference articles

  • Java exception interview questions
  • Guava’s exception utility class — Throwables