1. Architecture of exceptions

Definition: An exception is something that is different from normal, something that is wrong. In Java, abnormal situations in the process of program execution are called exceptions. Syntax errors and logical errors in the development process are not exceptions. When exceptions occur, Java will prevent the current method or scope.

Architecture of exceptions

  • Throwable: a superclass for all exceptions and errors in Java, with two subclasses Error and Exception.

Error: Indicates an Error that cannot be handled in the program. It indicates that a serious Error occurs in the running of the application program. Such errors typically indicate a problem with the JVM while the code is running. There are usually Virtual MachineError (Virtual machine running error), NoClassDefFoundError (class definition error), etc. For example, an OutOfMemoryError occurs when the JVM runs out of available memory. When such an error occurs, the JVM terminates the thread. Non-coding error. Therefore, applications should not handle such errors when they occur. Exception: An Exception that can be caught and handled by the program itself. There are runtimeExceptions and non-runtime exceptions, also known as checked exceptions runtime exceptions (unchecked exceptions) : The RuntimeException class and its subclasses represent errors that the JVM may experience while running. The compiler will not detect such abnormal, and does not require handling exceptions, such as use null object reference (NullPointerException), array subscript bounds (ArrayIndexOutBoundException). This type of exception is untraceable. It is usually caused by a program logic error. You can choose to capture and handle the exception or not handle the exception. Non-runtime exceptions (checked exceptions) : Exceptions in Exception other than RuntimeException and subclasses. The compiler checks for such exceptions. If such exceptions, such as IOException, occur in a program, the exception must be handled by either try-catch or throws with a throws statement. Otherwise, the compilation fails.

Look at compile-time and run-time exceptions in terms of program execution

  • Compile-time exception: an exception that occurs when a program is compiled (javac source filename.java)
  • Runtime exception: An exception that occurs while a program is running (Java bytecode file name)

2. Common exceptions

2.1. Runtime exception

  • NullPointerException: A pointer to an object that is null

  • ArrayIndexOutOfBoundException (array Angle the cross-border exception) StringIndexOutOfBoundException (string) seams…

  • ClassCastException (type conversion exception)

2.2. Compile-time exceptions (compile-time exceptions must be handled otherwise they will not run)

  • IOException

FileNotFoundException

  • ClassNotFoundException

2.3. Run Demo for common exceptions

package com.broky.exception.commonException;

import java.util.Scanner;

public class CommonEx {
    static void ArithmeticExceptionDemo(){
        int a = 10;
        int b = 0;
        int c = a / b;
        /*Exception in thread "main" java.lang.ArithmeticException: / by zero at com.broky.exception.ArithmeticEx.main(ArithmeticEx.java:7)*/
    }

    static void ClassCastExceptionDemo(){
        Object obj = new Double(1);
        String str = (String)obj;
        /*Exception in thread "main" java.lang.ClassCastException: class java.lang.Double cannot be cast to class java.lang.String (java.lang.Double and java.lang.String are in module java.base of loader 'bootstrap') at com.broky.exception.ClassCastEx.main(ClassCastEx.java:7)*/
    }

    static void InputMismatchExceptionDemo(){
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        System.out.println(num);
        /*asd Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at com.broky.exception.InputMismatchEx.main(InputMismatchEx.java:8)*/
    }

    static void NullPointerExceptionDemo(){
        int[] arr = null;
        System.out.println(arr[3]);

        /*Exception in thread "main" java.lang.NullPointerException: Cannot load from int array because "arr" is null at com.broky.exception.NullPointerEx.main(NullPointerEx.java:6)*/
    }

    static void NumberFormatExceptionDemo(){
        String str = "abc";
        int a = Integer.parseInt(str);
        /*Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) at java.base/java.lang.Integer.parseInt(Integer.java:660) at java.base/java.lang.Integer.parseInt(Integer.java:778) at com.broky.exception.NumberMismatchEx.main(NumberMismatchEx.java:6)*/
    }

    static void ArrayIndexOutOfBoundExceptionDemo(){
        int[] arr = new int[3];
        System.out.println(arr[3]);
        /*Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at com.broky.exception.XIndexOutOfBoundEx.main(XIndexOutOfBoundEx.java:6)*/

        String str = "abc";
        System.out.println(str.charAt(3));
        /*Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3 at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48) at java.base/java.lang.String.charAt(String.java:711)  at com.broky.exception.XIndexOutOfBoundEx.main(XIndexOutOfBoundEx.java:11)*/
    }

    public static void main(String[] args){ ArrayIndexOutOfBoundExceptionDemo(); }}Copy the code

3. Grasping model principle of anomaly

Exception throwing: If an exception occurs when a program executes code during execution, the JVM will create and throw an object of the exception type at the exception code and throw it to the caller of the program. Once an object has been thrown, subsequent code no longer runs and the program terminates. Exceptions are thrown as follows: (1) the system throws an exception; (2) Manual throws an exception. Exception fetching can be understood as an exception processing method, with try-catch-finally and throws (see exception handling for details).

4. Exception handling

4.1. Try-catch-finally

Put code in a try{}, and at runtime, an object of the exception class will be generated if the code emits an exception. The generated exception object will match the type of the exception of the catch. After the match is successful, it will be caught by the catch, and then run the code in the catch{}. Generally, the code in the catch is the code that handles the exception, such as returning the information and details of the exception. Once the exception is handled, the current try-catch structure is broken out

Code in finally is executed last whether or not an exception occurs

  • When catching multiple exception types, if there is a parent-child relationship, write the small range above and the large range below. If there’s no parent-child relationship, it doesn’t matter who’s on top or who’s down.
  • (1) LLDB etMessage() (e.pirintsrackTrace ()
  • Variables that are alive in the try structure cannot be called again after they leave the try structure. If you want to avoid this, you need to declare variables before the try and initialize them, and assign values inside the try.
  • If there is a return in finally, then the return must be in finally
  • Try-catch-finally structures can nest with each other
  • Lesson 1: Using the try-catch-finally to handle compile-time exceptions stops the program from reporting errors at compile time, but it can still report errors at run time. We use try-catch to delay a compile-time exception until run time.
  • Lesson 2: In development, run-time exceptions are common and usually not handled by try-catch, because handling or not handling is an error. The best way is to modify the code. For compile-time exceptions, it is important to consider exception handling.
       package com.broky.exception.demo02;

public class TryCatchFinally {
    public static void main(String[] args) {
        String str = "abc";

        try {
            int i = Integer.parseInt(str);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("Operational complete"); }}}Copy the code

4.2. Throws + Exception type

  • Throws the exception to the upper level of the method to solve the problem. If the upper level of the method cannot solve the problem, the exception will be thrown upward and finally thrown to the main method. This means that when the method is called in the main method, the exception needs to be resolved.

Of course, the main method can throw the exception up to the Java virtual machine without resolving it. If the Java virtual machine cannot resolve the exception, then the Java virtual machine is over

  • Throws + The exception type is written on the method declaration. Specifies the type of exception that may be thrown when this method executes.

Once an exception occurs during the execution of the method body, an exception class object will still be generated in the exception code. When this object meets the post-throws exception type, it will be thrown. The subsequent code of the exception code is no longer executed!

  • Tyr-catch-fianlly: The exception is actually handled. Throws the exception to the method caller without actually disposing of it.

Note: Throwing an exception up is also a way to handle exceptions

package com.broky.exception;

import java.io.FileNotFoundException;

public class ThrowsEx {
    public void setAge2(int age) throws FileNotFoundException {
        if (age < 0) {
            throw new FileNotFoundException("Input age less than 0"); }}public void TestsetAge2() throws FileNotFoundException {
        setAge2(2);
    }
    
    public static void main(String[] args) {
        try{ ThrowsEx.throwsExTest(); } catch (FileNotFoundException e) { e.printStackTrace(); }}}Copy the code

5. Override the rule thrown by method exceptions

In the following code, the main method passes a SuperClass object to the display method. So the call to s.thod in the display method is the method overridden by SubClass, a SubClass of SpuerClass. If the range of exceptions thrown by this method is greater than that of the SuperClass parent, the catch handling of the exception in display will not catch the exception.

package com.broky.exception;

import java.io.FileNotFoundException;
import java.io.IOException;

public class OverrideTest {
    public void display(SuperClass s) {
        try{ s.method(); } catch (IOException e) { e.printStackTrace(); }}public static void main(String[] args) {
        OverrideTest overrideTest = new OverrideTest();
        overrideTest.display(newSubClass()); }}class SuperClass {
    public void method() throws IOException {
        System.out.println("super"); }}class SubClass extends SuperClass {
    public void method() throws FileNotFoundException {
        System.out.println("sub"); }}Copy the code

6. How to choose try-catch-finally or throws in development? #

  • If a method overridden ina classification does not handle exceptions with throws, the method overridden by a subclass cannot use throws either. This means that if an exception exists ina method overridden by a subclass, it must be handled in tyr-catch-finally mode.
  • The method is executed in a sequence of calls to other methods, which are executed in a progressive manner. We suggest that these methods be processed using throws. Method A can be handled ina try-catch-finally manner.

Because if you’re trying to call d, if you’re trying to catch b, if B fails, you’re not going to return the data that a needs. Therefore, it is better to use throws to collect exceptions together before processing them.

  • Note: Do not use try-catch and throws together in a method, because the exception is already processed by using a try-catch. Throws are meaningless.

7. Manually throw exception throw#

There are two types of exceptions that can be thrown manually: runtime and compile-time.

When a runtime exception is thrown, you do not need to handle the exception thrown.

When a compile-time exception is thrown, you must handle the exception thrown.

See the code below for detailed parsing

package com.broky.exception;

/*Demo manually throws an exception */


import java.io.FileNotFoundException;

public class ThrowEx {

    // Manually throw a runtime exception
    public void setAge(int age) {
        if (age < 0) {
            throw new NullPointerException("Input age less than 0"); }}/* This method manually throws runtime exceptions. Runtime exceptions can be left unhandled */

    // Manually throw a compile-time exception
    public void setAge2(int age) throws FileNotFoundException {
        if (age < 0) {
            throw new FileNotFoundException("Input age less than 0"); }}Compile-time exceptions need to be handled. Throws throws this exception, meaning that the method does not handle the exception but throws it to the caller so that the caller must handle the exception. Note: we don't use a try catch to handle the exception ourselves. We throw an exception in a method, and the method itself does nothing. So exceptions in a method need to be thrown to the caller to handle. */


    public static void main(String[] args) {
        ThrowEx throwEx = new ThrowEx();

        throwEx.setAge(- 5); }}Copy the code

8. Custom exception classes

  • Inherit existing Exception structures: RuntimeExceptiona (not handled), Exception (needed to be handled)
  • Provide the global constant: serialVersionUID
  • Provides an overloaded constructor
package com.broky.exception;

public class MyException extends RuntimeException{
    static final long serialVersionUID = -1234719074324978L;

    public MyException(){}public MyException(String message){
        super(message);
    }

    public static void main(String[] args) {
        throw new MyException("Custom runtime exception");
        /*Exception in thread "main" com.broky.exception.MyException: Custom runtime exception at com. Broky. Exception. MyException. The main (15) MyException. Java: * /}}Copy the code

9. Exception Handling Exercises #

9.1. Determine the output of the following code #

package com.broky.exception.practice;

public class ExceptionTest {
    static void methodA() {
        try {
            System.out.println("Run method A");
            throw new RuntimeException("Method A manually throws A runtime exception");
        } finally {
            System.out.println("Finally with method A"); }}static void methodB() {
        try {
            System.out.println("Method of entry into B");
            return;
        } finally {
            System.out.println("Finally using method B"); }}public static void main(String[] args) {

        try {
            methodA();
        } catch (Exception e) {
            System.out.println(e.getMessage()); } methodB(); }}/* Answer Run method A to manually throw A runtime exception into method B using method B finally */
Copy the code

Parsing the running steps in debug:

  1. methodA();
  2. System.out.println(” Run A method “);
  3. Throw new RuntimeException(” method A manually throws RuntimeException “); Method A has not yet finished running, so there is no catch in main, but finally must be run, so the method finally must precede the catch in main
  4. System.out.println(” finally with A method “);
  5. atch (Exception e) {System.out.println(e.getMessage()); }
  6. methodB();

9.2. Comprehensive exercise on exception handling

Write an application EcmDef Java that receives two arguments from the command line, requiring that no negative numbers can be entered, and calculates the Number FormatException on the data type, missing command-line arguments (ArraylndexOutofBounds) Exception, Arithmetic Exception (0), and input negative numbers (EcDef custom exceptions).

Tip:

  1. An exception method (ECM) is defined in the main class (EcmDef) to divide two numbers.
  2. Use exception handling statements in the man(method for exception handling
  3. In the program, customize the exception class (EcDef) corresponding to input negative numbers.
  4. Runtime accepts the parameter Java EcmDef 20 10∥args[0]= “20” args[1]= “10” I
  5. The static method parseInt(String s) of the nterger class converts s to an int
package com.broky.exception.practice;

public class EcDef extends Exception{
    static final long serialVersionUID = -338751612344229948L;

    public EcDef(){}public EcDef(String str){
        super(str);
    }

}

package com.broky.exception.practice;

public class EcmDef {
    public static int ecm(int a, int b) throws EcDef, ArithmeticException {
        if (a < 0 || b < 0)
            throw new EcDef("Input data less than 0");
        if (b == 0)
            throw new ArithmeticException("Divisor cannot equal zero.");
        return a / b;
    }

    public static void main(String[] args) {
        int a = 0;
        int b = 0;

        try {
            a = Integer.parseInt(args[0]);
            b = Integer.parseInt(args[1]);

            System.out.println(ecm(a, b));
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Missing command line arguments"); e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (ArithmeticException e) { e.printStackTrace(); } catch (EcDef ecDef) { ecDef.printStackTrace(); }}}Copy the code