What is an exception

An Exception in Java is an event that occurs during the execution of a program and interrupts the normal instruction flow of the executing program.

Classification of anomalies

Throwable superclass for all errors or exceptions. Error and Exception both inherit from this class.

  1. The Error class refers to internal errors and resource exhaustion errors of the Java runtime system. The application does not throw such objects. If such an error occurs, all that is left is to inform the user and try to terminate the program safely.
  2. Exception is divided into run-time Exception RuntimeException and compile-time Exception CheckedException.

example

Error, heap overflow, stack overflow, etc. RuntimeExceptio is a programmer’s problem. It may be a superclass of exceptions thrown during the normal running of the Java VIRTUAL machine. Common exceptions include NullPointerException and ClassCastException. CheckedException: The Java compiler forces an application to catch an exception during compilation.

How to handle exceptions

There are three forms of throwing exceptions: throw, throw, and automatic throwing by the system. The system will automatically throw an exception when some logic error, doctrine error, or type conversion error occurs in the program statement.

public void feng { int a = 1, b =0; System.out.println(a/b); // The ArithmeticException exception is automatically thrown}Copy the code

Throws the difference between throws and throws

A throw is a statement that throws an exception, usually inside a block of code. It is the programmer’s initiative to throw a particular type of exception when a certain logic error occurs in the program. The programmer uses the program logic to decide which exception to throw manually. Throws is a declaration that a method may throw an exception. (used when declaring a method to indicate that the method may throw an exception)

Public void list() {if (head.next == null) {throw new RuntimeException(" Current list is empty "); }}Copy the code

Throws occurs in the header of a method function; Throw occurs in the body of a function.

  public static void sparseToFile() throws IOException {
  }
Copy the code
  1. Throws represents a possibility of exceptions that do not necessarily occur; A throw throws an exception, and executing a throw must throw some kind of exception object.

  2. Throw and throw methods are declared to indicate that this method does not handle exceptions and throws them to the method caller. Comparison is generally considered negative exception handling.

  3. Throws represents a possibility of exceptions that do not necessarily occur; A throw throws an exception, and executing a throw must throw some kind of exception object.