: Notebook: This article is filed under “blog”

: Keyboard: The sample code in this article is archived under: “Javacore”

Abnormal framework



Throwable

ThrowableAre all errors in the Java language (Error) and exceptions (Exception) superclass.

Throwable contains a snapshot of the stack executed by its thread when it was created, and provides interfaces such as printStackTrace() to get information such as stack trace data.

Main methods:

  • fillInStackTrace– Populates with the current call stack hierarchyThrowableObject stack hierarchy, added to any previous information in the stack hierarchy.
  • getMessage– Returns detailed information about the exception that occurred. The news is inThrowableClass in the constructor of the.
  • getCause– Return aThrowableObject indicates the cause of the exception.
  • getStackTrace– Returns an array containing the stack hierarchy. The element with subscript 0 represents the top of the stack, and the last element represents the bottom of the method call stack.
  • printStackTrace– printtoString()Results and stack hierarchy toSystem.err, the error output stream.
  • toString– usegetMessageThe result is returned on behalf ofThrowableObject.

Error

Error is a subclass of Throwable. Error represents a serious problem that a reasonable application should not attempt to catch. Most of these errors are exceptions. The compiler does not check for Error.

Common Error:

  • AssertionError– Assertion error.
  • VirtualMachineError– The VM is faulty.
  • UnsupportedClassVersionError– The Java class version is incorrect.
  • StackOverflowError– Stack overflow error.
  • OutOfMemoryError– Memory overflow error.

Exception

Exception is a subclass of Throwable. Exception represents a condition that a reasonable application might want to capture.

The compiler checks for Exception. ** This type of exception cannot pass compilation unless it is declared thrown with throws or caught with a try catch.

Common Exception:

  • ClassNotFoundException– The application throws this exception when it tries to load a class but cannot find the corresponding class.
  • CloneNotSupportedException– Thrown when the Clone method of the Object class is called to clone an Object whose class cannot implement the Cloneable interface.
  • IllegalAccessException– Throws this exception when access to a class is denied.
  • InstantiationException– Thrown when an attempt is made to create an instance of a Class using the newInstance method of a Class whose specified Class object cannot be instantiated because it is an interface or an abstract Class.
  • InterruptedException– Raised when a thread is interrupted by another thread.
  • NoSuchFieldException– Requested variable does not exist.
  • NoSuchMethodException– Requested method does not exist.

Example:

public class ExceptionDemo {
    public static void main(String[] args) {
        Method method = String.class.getMethod("toString".int.class); }};Copy the code

An error occurs when attempting to compile the runtime:

Error: (7, 47) Java: failing to report the exception Error Java. Lang. NoSuchMethodException; It must be caught or declared for throwingCopy the code

RuntimeException

RuntimeException is a subclass of Exception. RuntimeException is a superclass of exceptions that might be thrown during normal operation of the Java Virtual machine.

The compiler does not check for RuntimeException. ** When such an exception may occur in a program, the program will compile if it is not thrown with either a throw declaration or caught with a try catch statement.

Example:

public class RuntimeExceptionDemo {
    public static void main(String[] args) {
        // There is an exception
        int result = 10 / 0;
        System.out.println("The result of dividing two numbers:" + result);
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); }};Copy the code

Runtime output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
	at io.github.dunwu.javacore.exception.RumtimeExceptionDemo01.main(RumtimeExceptionDemo01.java:6)
Copy the code

Common RuntimeException:

  • ArrayIndexOutOfBoundsException– An exception thrown when accessing an array with an invalid index. If the index is negative or greater than or equal to the array size, it is an invalid index.
  • ArrayStoreException– An exception thrown when attempting to store an object of the wrong type into an array of objects.
  • ClassCastException– Thrown when an attempt is made to cast an object to a subclass that is not an instance.
  • IllegalArgumentException– The exception thrown indicates that an invalid or incorrect argument was passed to the method.
  • IllegalMonitorStateException– An exception thrown indicates that a thread has attempted to wait for an object’s monitor, or has attempted to notify other monitors that are waiting for an object without specifying a monitor itself.
  • IllegalStateException– A signal generated when a method is called at an illegal or inappropriate time. In other words, the Java environment or Java application is not in the proper state required by the request operation.
  • IllegalThreadStateException– An exception thrown when the thread is not in the proper state required by the requested operation.
  • IndexOutOfBoundsException– Thrown when a sort index (such as sorting an array, a string, or a vector) is out of range.
  • NegativeArraySizeException– Throws this exception if the application tries to create an array of negative size.
  • NullPointerException– Throws this exception when an application tries to use NULL where objects are needed
  • NumberFormatException– Thrown when an application tries to convert a string to a numeric type, but the string cannot be converted to a proper format.
  • SecurityException– An exception thrown by the security manager indicating a security violation.
  • StringIndexOutOfBoundsException– This exception is thrown by the String method indicating that the index is either negative or beyond the size of the String.
  • UnsupportedOperationException– Throws this exception when the requested operation is not supported.

Custom exception

Custom exception class, only need to inheritExceptionRuntimeExceptionCan.

Example:

public class MyExceptionDemo {
    public static void main(String[] args) {
        throw new MyException("Custom exception");
    }

    static class MyException extends RuntimeException {
        public MyException(String message) {
            super(message); }}}Copy the code

Output:

Exception in thread "main" io.github.dunwu.javacore.exception.MyExceptionDemo$MyException: custom exception at IO. Making. Dunwu. Javacore. Exception. MyExceptionDemo. Main (MyExceptionDemo. Java: 9)Copy the code

An exception is thrown

If you want to throw an exception explicitly in a program, use throw and throws.

If a method does not catch a checking exception, the method must be declared using the THROWS keyword. Throws the keyword at the end of the method signature.

Throw the sample:

public class ThrowDemo {
    public static void f(a) {
        try {
            throw new RuntimeException("Throw an exception");
        } catch(Exception e) { System.out.println(e); }}public static void main(String[] args) { f(); }};Copy the code

Output:

Java. Lang. RuntimeException: throw an exceptionCopy the code

You can also use the throw keyword to throw an exception, whether it is newly instantiated or just caught.

Throws the sample:

public class ThrowsDemo {
    public static void f1(a) throws NoSuchMethodException, NoSuchFieldException {
        Field field = Integer.class.getDeclaredField("digits");
        if(field ! =null) {
            System.out.println("Reflection gets digits method successful");
        }
        Method method = String.class.getMethod("toString".int.class);
        if(method ! =null) {
            System.out.println("Reflection gets toString method successfully"); }}public static void f2(a) {
        try {
            // if f1 is called without a try catch, an error will be reported at compile time
            f1();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch(NoSuchFieldException e) { e.printStackTrace(); }}public static void main(String[] args) { f2(); }};Copy the code

Output:

Reflection method for who successfully Java. Lang. NoSuchMethodException: java.lang.String.toString(int) at java.lang.Class.getMethod(Class.java:1786) at io.github.dunwu.javacore.exception.ThrowsDemo.f1(ThrowsDemo.java:12) at io.github.dunwu.javacore.exception.ThrowsDemo.f2(ThrowsDemo.java:21) at io.github.dunwu.javacore.exception.ThrowsDemo.main(ThrowsDemo.java:30)Copy the code

Throws throws

  • Throws are used on functions and throws are used within functions.
  • Throws after the exception class, can be with more than one, use a comma to distinguish; A throw is followed by an exception object.

Catch exceptions

Use the try and catch keywords to catch exceptions. Try catch blocks are placed where exceptions are likely to occur.

The syntax is as follows:

try {
    // Block of code where an exception may occur
} catch (Exception e1) {
    // Catch and handle the Exception type Exception thrown by try
} catch (Exception2 e2) {
    // Catch and handle Exception2, the exception type thrown by try
} finally {
    // The block of code that will be executed whether or not an exception occurs
}
Copy the code

In addition, after JDK7, we can also simplify the code by catching multiple exceptions as follows:

try {
    // Block of code where an exception may occur
} catch (Exception | Exception2 e) {
    // Catch and handle the type of exception thrown by a try
} finally {
    // The block of code that will be executed whether or not an exception occurs
}
Copy the code
  • trytryStatements are used to listen. The code to be listened on (code that might throw an exception) is placed intryStatement block, whentryWhen an exception occurs within a block, it is thrown.
  • catchcatchThe statement contains declarations for the type of exception to catch. When an exception occurs in a protected code block,tryAt the back of thecatchThe block will be examined.
  • finallyfinallyBlocks are always executed, regardless of exceptions.try catchIt is not necessary after the statementfinallyStatements.finallyOften used in situations such as: BecausefinallyBlocks are always executed, so those intryPhysical resources (such as database connections, network connections, and files) that are opened in a code block and must be reclaimed are typically placed infinallyStatement block to release resources.
  • try,catch,finallyLocal variables in three code blocks cannot be shared.
  • catchBlock attempts to catch an exception when it is followedcatchBlocks are declared from the top down, and once matched, they are not executed further down. So if the sametryBlock under multiplecatchException types have a parent-child relationship, and subclass exceptions should be placed first and superclass exceptions next.

Example:

public class TryCatchFinallyDemo {
    public static void main(String[] args) {
        try {
            // There is an exception
            int temp = 10 / 0;
            System.out.println("The result of dividing two numbers:" + temp);
            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        } catch (ArithmeticException e) {
            System.out.println("Something is wrong:" + e);
        } finally {
            System.out.println("Execute this code regardless of whether an exception occurs."); }}};Copy the code

Runtime output:

Exception: Java. Lang. ArithmeticException: / by zero regardless of whether an exception, this code is executedCopy the code

Abnormal chain

An exception chain takes an exception object as a parameter to construct a new exception object that will contain information about the previous exception.

By using exception chains, we can improve code comprehension, system maintainability, and friendliness.

Throws throws throws for superior processing; throws throws throws for superior processing; throws throws throws for superior processing; throws throws throws for superior processing. Catch (v.) The try… We don’t need to do any processing for the catch block of catch, just use the keyword throw to actively throw our encapsulated exception information. Throws continue with the method exception after passing the keyword throws. Its upper layers can do the same, and so on to produce a chain of exceptions.

Example:

public class ExceptionChainDemo {
    static class MyException1 extends Exception {
        public MyException1(String message) {
            super(message); }}static class MyException2 extends Exception {
        public MyException2(String message, Throwable cause) {
            super(message, cause); }}public static void f1(a) throws MyException1 {
        throw new MyException1("Appear MyException1");
    }

    public static void f2(a) throws MyException2 {
        try {
            f1();
        } catch (MyException1 e) {
            throw new MyException2("Appear MyException2", e); }}public static void main(String[] args) throws MyException2 { f2(); }}Copy the code

Output:

Exception in thread "main" io.github.dunwu.javacore.exception.ExceptionChainDemo$MyException2: Appear MyException2 at IO. Making. Dunwu. Javacore. Exception. ExceptionChainDemo. F2 (ExceptionChainDemo. Java: 29) at io.github.dunwu.javacore.exception.ExceptionChainDemo.main(ExceptionChainDemo.java:34) Caused by: io.github.dunwu.javacore.exception.ExceptionChainDemo$MyException1: Appear MyException1 at IO. Making. Dunwu. Javacore. Exception. ExceptionChainDemo. F1 (ExceptionChainDemo. Java: 22) at io.github.dunwu.javacore.exception.ExceptionChainDemo.f2(ExceptionChainDemo.java:27) ... 1 moreCopy the code

Read more: juejin.cn/post/684490…

The exception chain is explained in detail in this article.

Abnormal Precautions

Finally override exception

A return in finally in Java exception handling overrides the return and throw statements ina catch block, so Java does not recommend using a return statement in finally.

In addition, the throw statement in finally overrides the return and throw statement in the catch block.

Example:

public class FinallyOverrideExceptionDemo {
    static void f(a) throws Exception {
        try {
            throw new Exception("A");
        } catch (Exception e) {
            throw new Exception("B");
        } finally {
            throw new Exception("C"); }}public static void main(String[] args) {
        try {
            f();
        } catch(Exception e) { System.out.println(e.getMessage()); }}}Copy the code

Output: C

Override methods that throw exceptions

When a subclass overrides a function with a parent class throws declaration, the exception declared by the subclass must be within the scope of the parent class exception. The exception handler used to handle the parent class’s throws method must also apply to the subclass’s throws method. This is to support polymorphism.

Example:

public class ExceptionOverrideDemo {
    static class Father {
        public void start(a) throws IOException {
            throw newIOException(); }}static class Son extends Father {
        @Override
        public void start(a) throws SQLException {
            throw newSQLException(); }}public static void main(String[] args) {
        Father obj1 = new Father();
        Father obj2 = new Son();
        try {
            obj1.start();
            obj2.start();
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code

The above example will compile an error because:

Because the essence of the exception thrown by Son is SQLException, IOException cannot handle it. So this try catch here can’t handle an exception in Son. You can’t do polymorphism.

Exceptions and threads

If a Java program has only one thread, exceptions that are not handled by any code cause the program to terminate. If Java programs are multithreaded, exceptions that are not handled by any code simply cause the thread in which the exception originated to terminate.

Best practices

  • Use checking exceptions for recoverable cases and runtimeExceptions for programming errors
  • Java standard exceptions are preferred
  • Throws an exception corresponding to the abstraction
  • Include information to catch failures in the detail message
  • Minimize the size of the try code block
  • Try to narrow down the anomaly. For example, if knowingly trying to capture aArithmeticException“, should catchArithmeticException“Rather than catch a wider rangeRuntimeExceptionAnd evenException.
  • Try not tofinallyBlock throws an exception or returns a value
  • Do not ignore exceptions; once they are caught, they should be handled, not discarded
  • Exception handling is inefficient, so do not use exceptions for business logic processing
  • Each type of exception must be separately logged, classified and managed, because sometimes only logical exceptions are shown to third-party o&M, rather than more detailed information.
  • How are exceptions classified
    • Logical exceptions. These exceptions are caused by users when services fail to be processed as expected.
    • Code error. This type of exception is used to describe the development of code errors, such as NPE, ILLARG, are programmer created bugs.
    • A special exception is used in specific service scenarios to describe an unexpected situation in a specified job that cannot be handled in advance.

Read more:

  • Chapter 9 Exceptions in Effective Java
  • Handle your Java exceptions gracefully

summary





The resources

  • Java Programming ideas
  • JAVA Core Technologies (Volume 1)
  • Chapter 9 Exceptions in Effective Java
  • Handle your Java exceptions gracefully
  • Juejin. Cn/post / 684490…
  • www.cnblogs.com/skywang1234…
  • www.importnew.com/26613.html