Explanation of Java Exception Types and Handling Instances

  • 2021-10-25 06:43:46
  • OfStack

Directory 1. Description of Exception 2. System of Exception 3. Classification of Exception 4. Catch Form of Exception Handling 5. Principle of Exception Handling 6. finally7. Application of Exception
8. Precautions for exceptions: Summary

1. Description of the exception

An unexpected event occurs when a program is running, which prevents the program from executing normally as expected by the programmer. This is an exception. When an exception occurs, the program is left to fend for itself and immediately exits and terminates. In Java, that is, Java, errors that occur during compilation or running or during running.

Java provides a better solution: exception handling mechanism.

Exception handling mechanism can make the program deal with exceptions according to the pre-set exception handling logic of the code when exceptions occur, so that the program can resume normal and continue to execute as much as possible, and keep the code clear.

Exceptions in Java can be thrown when statements in functions are executed, or can be manually thrown by programmers through throw statements. As long as exceptions are generated in Java programs, exceptions will be encapsulated with an exception object of corresponding type, and JRE will try to find exception handlers to handle exceptions.

Exception refers to an abnormal condition that occurs during operation. In java, the abnormal situation is described and the object is encapsulated in the form of class. A class that describes an abnormal condition becomes an exception class. Separate normal code from problem handling code to improve readability. In fact, java encapsulates the problem into an object through the idea of object-oriented, and describes it with exception classes.

2. Anomalous system

Two major categories:

hrowable: Throwable exceptions, whether error or exception, should be thrown as soon as the problem occurs, known and handled by the caller. The characteristic of this system is that Throwable and all its subclasses are polishable.

What exactly does disposability mean? How to embody throwing ability?

It is embodied by two keywords. throws throw All classes and objects that can be manipulated by these two keywords are polishable. Subclass 1 1 is as unprocessable as. ---Error Features: It is a serious problem thrown by jvm. This kind of problem occurs without pertinence, and the program is modified directly. Subclass 2) can be handled.----Exception, the problem is thrown to the caller, who is thrown to whom. Features: Subclass suffix name is to use its parent class name as suffix name, which is very readable!

Example: For example, customize a negative corner mark exception, and encapsulate it into an object with object-oriented ideas.

Note: If you call a class an exception class, you must inherit the exception class. Because only the subclasses of the exception system have throwing property.

class FuShuIndex extends Exception{
                // Constructor   And class name 1 Sample 
                FuShuIndex(){  
                }
                // Definition 1 Constructors with arguments 
                FuShuIndex(String msg){
                    // Call Exception Exception function with parameters in 
                    super(msg);  
                }
            }
             Principal function  throws FuShuIndex : {
               int[] arr = new int[3];
               method(arr,-7);
            }
            public static int method(int[] arr,int index) throws arrIndexexception {
                 if (index<0){
                    throw new arrIndexexception(" The corner marker of an array cannot be negative ");
                 }
                return arr[index];
            }

3. Classification of anomalies:

The exception detected at compile time is Exception and its subclasses, except that the special subclass RuntimeException system fails to compile without processing!

Once this kind of problem 1 appears, I hope to detect it at compile time, so that this kind of problem can be dealt with accordingly, and all these problems can be dealt with pertinently.

Undetected exceptions at compile time (runtime exceptions): RuntimeException and its subclasses

Can handle can not handle, compile can pass, run time will detect! This kind of problem occurs, can't let the function continue, the operation can't run, more because of the call, or caused by the change of internal state. This kind of problem 1 generally does not deal with, compiles directly through, in the run time, lets the caller when the program forcibly stops, lets the caller carries on the correction to the code.

Differences between throws and throw:

throws is used on functions--declarations throw is used within functions and can be thrown as many as possible, separated by commas. Throw throws throws exception classes and can throw more than one. throw throws an exception object.

4. The catch form of exception handling

This is how exceptions can be targeted.

Format:


try{
            // Code that needs to be detected for exceptions 
        }
        catch( Exception class   Variable )// This variable is used to receive the exception object that occurred {
            // Handling exception code 
        }
        finally{
            //1 Code that will be executed 
      }

Example


class FuShuIndex extends Exception{
            // Constructor   And class name 1 Sample 
            FuShuIndex(){  
            }
            // Definition 1 Constructors with arguments 
            FuShuIndex(String msg){
                // Call Exception Exception function with parameters in 
                super(msg);  
            }
  }

Main function: We don't need throws to throw it, so we catch the exception ourselves


{
           int[] arr = new int[3];
           try{
           method(arr,-7);
           }catch(arrIndexexception a){
                a.printStackTrace();//jvm The default exception handling mechanism is to call this method of the exception object. 
                System.out.println(" The corner mark of the array is abnormal! ! ! ");// Customize the information printed after capture 
                System.out.println(a.toString());// Print the information of 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(" The corner marker of an array cannot be negative ");
             }
            return arr[index];
 }

One try corresponds to multiple catch:

In the case of multiple catch, the catch of the parent class should be placed at the bottom, otherwise it will compile to be empty.

5. Principles for exception handling

If an exception to be detected is thrown inside the function, it must be declared on the function, or it must be caught inside the function with ES90catch, otherwise the compilation fails.

If a function declaring an exception is called, either try, catch or throws, or the compilation fails.

When is catch? When is throws?

Functional content can be solved with catch. If it can't be solved, tell the caller with throws, and the caller will solve it.

If a function throws multiple exceptions, it must have corresponding multiple catch for targeted processing when calling.

If there are several anomalies that need to be detected inside, throw a few anomalies, and throw a few anomalies on catch.

6. finally

Usually used to close (free) resources. It must be implemented. Unless the jvm virtual machine hangs up.

Example: When you go out to play, you must close the door, so if you put the action of closing the door in finally, you must execute it.

The finally code block is used to release resources when operations such as closing connections are involved.

try catch finally code block combination features:

try catch finally: finally can be defined when resources need to be released try catch (multiple): finally may not be defined when no resources need to be released try finally: Exception handling is not handled I don't care, but I have to close the resource because I opened the resource and have to close the resource internally.

Example:


try{
                    // Connect to a database 
                }
                    // No catch It means not handling exceptions, but simply catching exceptions 
                finally{
                    // Close the connection 
                }

7. Application of anomalies

Examples of teachers using computers to give lectures:

Computer category:


public class Computer {
                private int state = 2;
                public void run() 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 startup ");
                }
                public void chongqi(){
                    state = 0;
                    System.out.println(" Restart the computer! ");
                }
  }

Teacher category:


public class Teacher {
            private String name;
            private Computer computer;
            Teacher(String name){
                this.name = name;
                computer = new Computer();
            }

            void teach() throws maoyanExcption{
                try {
                    computer.run();
                    System.out.println(this.name + " Began to use computers to give lectures ");
                } catch (lanpingExcption l) {
                    l.printStackTrace();
                    computer.chongqi();
                    teach();// Lecture again after restarting 
                } catch (maoyanExcption m) {
                    m.printStackTrace();
                    test();
                    throw m;
                }
            }

            public void test(){
                System.out.println(" Let's practice by ourselves ~ ");
            }

  }

Blue Screen Exception Class:


public class lanpingExcption extends Exception{
            lanpingExcption (String msg){
                 super(msg);
            }
 }

Smoking anomalies:


public class maoyanExcption extends Exception {
            maoyanExcption (String msg){
                super(msg);
            }
}

Main function:


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

8. Precautions for anomalies:

If the method of the parent class throws an exception when the subclass overrides the method of the parent class, the method of the subclass can only throw the exception of the parent class or the subclass of the exception. If the parent class throws multiple exceptions, the child class can only throw a subset of the parent class's exceptions. Subclass overrides parent class and can only throw exceptions or subclasses of parent class. If the method of the parent class does not throw an exception, it must not be thrown when the subclass is overwritten.

Summarize


Related articles: