This is my third article about getting started


1. Description of exceptions

  • An exception is an abnormal condition that occurs during runtime.
  • In Java, abnormal conditions are described and objects are encapsulated in the form of classes.
  • Classes that describe abnormal conditions are called exception classes.
  • Improve readability by separating normal code from problem solving code.
  • In fact, an exception is a problem that Java encapsulates into an object through object-oriented thinking, and is described by an exception class.

Second, abnormal system

  • Two broad categories:

    • Hrowable: An exception that can be thrown, whether error or exception, when a problem occurs, for the caller to know about and handle.
    • This system is characterized by Throwable and all of its subclasses being Throwable.
  • What exactly does disposability mean? So how do you represent disposability?

    • Through two key words.
    • Throws all classes and objects that can be operated on by these two keywords are throwable.
    • Subclass 1 is generally unprocessable. — – the Error
    • Features: This is a serious problem thrown by the JVM, which is usually not addressed, directly modify the program.
    • Subclass 2) can be handled. ————Exception, the problem is thrown to the caller, who needs to throw to whom.
    • Features: subclass suffix name is to use its parent class name as a suffix name, strong reading!
  • Example: For example, a custom negative corner exception is encapsulated as an object using object-oriented thinking.

    • Note: If a class is called an exception class, it must inherit the exception class. Because only subclasses of the exception system are throwable.
  • class FuShuIndex extends Exception{
                    The constructor is the same as the class name
                    FuShuIndex(){  
                    }
                    // Define a constructor that takes arguments
                    FuShuIndex(String msg){
                        // Call Exception with arguments
                        super(msg); }} main functionthrowsFuShuIndex: {int[] arr = new int[3];
                   method(arr,-7);
                }
                public static int method(int[] arr,int index) throws arrIndexexception {
                     if (index<0) {throw new arrIndexexception("Array markers cannot be negative.");
                     }
                    return arr[index];
                }
    Copy the code

Iii. Classification of anomalies:

  • Exceptions detected at compile time are exceptions and all of their subclasses, except the RuntimeException special subclass.
    • Once this kind of problem appears, hope to detect at compile time, let this kind of problem have the corresponding way to deal with, such kind of problem can be targeted to deal with.
  • Exceptions not detected at compile time (runtime exceptions) : RuntimeException and its subclasses
    • Can be processed or not processed, compilation can pass, run time detection!
    • This problem occurs when the function cannot continue, the operation cannot run, more because of the call, or caused by the internal state change. This kind of problem is generally not handled, directly compiled through, at run time, let the caller when the program forced to stop, let the caller to fix the code.
  • Throws and throws:
    • Throws is declared using ———— on functions
    • Within a function, more than one can be thrown, separated by a comma. Thrown — –
    • Throws an exception class. Multiple exception classes can be thrown.
    • Throw throws an exception object.

Fourth, the capture form of exception handling

  • This is how exceptions can be targeted.

  • Format:

    • try{
                  // The code that needs to be detected
              }
              catch(Exception class variable)// This variable is used to receive the exception object that occurs {
                  // Handle exception code
              }
              finally{
                  // The code that must be executed
            }
      Copy the code
  • sample

    • class FuShuIndex extends Exception{
                  The constructor is the same as the class name
                  FuShuIndex(){  
                  }
                  // Define a constructor that takes arguments
                  FuShuIndex(String msg){
                      // Call Exception with arguments
                      super(msg); }}Copy the code
    • Main function: Without throwing throws, we catch the exception ourselves

    • {
                 int[] arr = new int[3];
                 try{
                 method(arr,-7);
                 }catch(arrIndexexception a){
                      a.printStackTrace();// The JVM's default exception handling mechanism is to call this method on the exception object.
                      System.out.println("Array corner exception!!");// Customize the information to print after capture
                      System.out.println(a.toString());// Prints information about the exception object
                      System.out.println(a.getMessage());// Get the information defined by our custom throw}}public static int method(int[] arr,int index) throws arrIndexexception {
                   if (index<0) {throw new arrIndexexception("Array markers cannot be negative.");
                   }
                  return arr[index];
       }
      Copy the code
    • A try corresponds to multiple catches:

      • In multi-catch cases, the catch of the parent class must be placed at the bottom, otherwise it will compile to empty.

5. Principles of exception handling

  • If an exception is thrown inside a function that needs to be checked, it must be declared on the function or caught with a try catch inside the function, otherwise the compilation fails.
  • If a function that declares an exception is called, either try catch or throws, otherwise the compilation fails.
  • When is the catch? Throws when?
    • Function content can be solved, use catch.
    • If no, use throws to tell the caller, and the caller will solve the problem.
  • A function that throws more than one exception must be called with a corresponding catch to handle it.
    • If there are several internal exceptions that need to be detected, several exceptions will be thrown, and several exceptions will be caught.

Sixth, the finally

  • Usually used to close (free) resources. It has to be done. Unless the JVM vm hangs.

  • Example: When you go out to play, you must close the door, so put the door in finally.

  • When operations such as closing a connection are involved, finally blocks are used to release resources.

  • Try catch finally

    • Try catch finally: You can define a finally when a resource needs to be released

    • Try catch(multiple) : You may not define finally when there are no resources to release

    • I don’t care if I don’t handle it, but I have to close the resource because I started it. I have to close the resource internally.

      • Example:

      • try{
                            // Connect to the database
                        }
                            // No catch means to catch an exception without handling it
                        finally{
                            // Close the connection
                        }
        Copy the code

7. Application of exceptions

  • Example of the teacher using a computer:

  • Computer class:

    • public class Computer {
                      private int state = 2;
                      public void run(a) throws lanpingExcption,maoyanExcption{
                          if (state == 1) {throw new lanpingExcption("Computer blue screen!");
                          }else if (state == 2) {throw new maoyanExcption("The computer is smoking.");
                          }
                          System.out.println("Computer boot up");
                      }
                      public void chongqi(a){
                          state = 0;
                          System.out.println("Restart your computer!"); }}Copy the code
  • The teacher class:

    • public class Teacher {
                  private String name;
                  private Computer computer;
                  Teacher(String name){
                      this.name = name;
                      computer = new Computer();
                  }
      
                  void teach(a) throws maoyanExcption{
                      try {
                          computer.run();
                          System.out.println(this.name + "Start lecturing on the computer.");
                      } catch (lanpingExcption l) {
                          l.printStackTrace();
                          computer.chongqi();
                          teach();// Restart and start again
                      } catch (maoyanExcption m) {
                          m.printStackTrace();
                          test();
                          throwm; }}public void test(a){
                      System.out.println("Practice by yourselves."); }}Copy the code
  • Blue screen exception class:

    • public class lanpingExcption extends Exception{
                  lanpingExcption (String msg){
                       super(msg); }}Copy the code
  • Smoke exception class:

    • public class maoyanExcption extends Exception {
                  maoyanExcption (String msg){
                      super(msg); }}Copy the code
  • Main function:

    • public class Testmain {
                  public static void main (String[] args){
                      Teacher teacher = new Teacher("Mr. Ding");
                      try {
                          teacher.teach();
                      } catch (maoyanExcption m) {
                          //m.printStackTrace();
                          System.out.println("..."); }}}Copy the code

Eight, abnormal precautions:

  • When a subclass overrides a method of a superclass, if the method of the superclass throws an exception, the method of the subclass can only throw an exception of the superclass or a subclass of that exception.
  • If the parent class throws more than one exception, the subclass can only throw a subset of the parent class exception.
  • A subclass overrides its parent class and can only throw exceptions or subclasses of the parent class.
  • If a method of the parent class does not throw an exception, subclass overrides must not throw.

Since then all the end, the above are personal words, if there is wrong, please point out, we communicate progress together. Thank you very much!