This is the 10th day of my participation in Gwen Challenge

Abnormal classification

Error

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.

Exception (e.g. RuntimeException, CheckedException)

Exception has two branches, a RuntimeException and a CheckedException.

RuntimeException (RuntimeException)

Such as NullPointerException and ClassCastException.

RuntimeException is a superclass of exceptions that might be thrown during normal operation of the Java Virtual machine. If a RuntimeException occurs, it must be the programmer’s fault.

CheckedException (check for exceptions)

For example, IOException and SQLException caused by I/O errors.

CheckedException: an external error that occurs during compilation. The Java compiler forces your program to try and catch an exception.

  1. Attempted to read data at the end of the file

  2. Attempted to open a malformed URL

  3. An attempt was made to find a class object based on a given string representing a class that does not exist

How to handle exceptions

Throws a problem to the caller (throw,throws).

There are three types of throwing exceptions: throw, throws, and automatic throwing by the system.

public static void main(String[] args) { 
 String s = "abc"; 
 if(s.equals("abc")) { 
     throw new NumberFormatException(); 
 } else{ System.out.println(s); }}int div(int a,int b) throws Exception{
    return a/b;
}
Copy the code

Try catch Specifies the processing method for catching exceptions.

Throws and throws

Different location

Throws is used on functions, followed by exception classes, which can be multiple. A throw is used inside a function, followed by an exception object.

Function of different

Throws is used to declare exceptions, so that the caller only knows the possible problems of the function, and can provide a pre-processing formula. The throw throws a specific problem object, and by the time the throw is executed, the function is done, jumping to the caller and throwing the specific problem object to the caller. That is, if the throw statement stands on its own, do not define other statements below, because they cannot be executed.

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.

conclusion

Both are passive ways of handling exceptions, just throwing or possibly throwing exceptions, but not handled by the function. The actual handling of exceptions is handled by the upper level of the function call.