java exception handling mechanism (Introduction)

Posted by nerotic on Wed, 26 Jan 2022 10:11:18 +0100

java exception handling mechanism (Introduction)

Overview of exception handling mechanism

Errors and exceptions

error

  • The program enters an endless loop or memory overflow, which is called an error. The error can only be solved in the programming stage. The program itself cannot be solved when running. It can only rely on the intervention of other programs, otherwise it will always be in an abnormal state.

abnormal

  • It is the result that cannot be predicted occurs during the operation of the program. When an exception occurs, the exception is thrown, causing the program to stop.

  • When a java program violates the semantic rules of the Java language, the Java virtual machine will send an error signal.

      Official source code explanation:
     (1)Exception class Exception(extends Throwable),Is from JDK1.0 The version has been available since the beginning, Class exceptions and their subclasses
     yes Throwable A form that represents the conditions that a reasonable application may want to capture.
     (2) Class exceptions and any exceptions that do not belong to RuntimeException Subclasses of subclasses are all check exceptions. If method or
      The execution of the constructor can throw the selected exception and propagate outside the method or constructor boundary
      Method or constructor throws Clause to declare the selected exception.
    

Hierarchy of exception classes

Structure diagram:

Subclass of Exception class

(1) RuntimeException -- runtime exception class
It mainly includes the following abnormal subclasses

  • ArithmeticException arithmetical exception class: indicates the arithmetical problem encountered in exception, such as division by 0.
  • ArrayIndexOutBoundsException array index out of bounds exception class: when the index value is negative or greater than the array length, an exception thrown when accessing the array with an illegal index will appear.
  • ArrayStoreException array element type mismatch exception class: an attempt was made to store a value that does not match the array type into the array.
  • NumberFormatException number formatting exception: this exception class is thrown when an attempt to convert a string to a numeric type cannot be run.
  • ClassCastException type cast exception class: an attempt was made to cast an object reference to an inappropriate type
  • IndexOutOfBoundsexception subscript out of bounds exception class: subscript out of bounds.
  • Null pointerexception null pointer exception class: an attempt was made to use an empty object reference.
  • SecurityException security violation exception class: security violation detected.

(2) NoSuchMethodException -- method did not find exception class
(3)java.awt.AWTException -- Graphical interface exception class
(4)java.io.IOException -- input / output exception class

  • IOException: the requested I/O operation did not complete normally

  • EOFException: end of file encountered before normal end of input operation.

  • FileNotFoundException: the file specified by the file name string was not found in the file system.
    (5) Other subclasses of Exception class

  • EmptyStackException: attempted to access an element in an empty stack

  • NoSuchFieldException: an attempt was made to access a domain that does not exist

  • NoSuchMethodException: an attempt was made to access a method that does not exist

  • ClassNotFoundException: the class or interface with the specified name was not found

  • CloneNotSupportedException: clone a class that does not implement the clonable interface

  • IllagalAccessException: attempts to load a class with a string that gives complete path information. However, the currently executing method cannot access the specified class because the class is not public or in another package

  • InstantiationException: an attempt was made to create an object instance using the newInstance method of Class, but the specified object was not instantiated because it was an interface, abstract Class, or array

  • InterruptedException: the current Thread is waiting while another Thread interrupts the current Thread using Thread's interrupt() method

Subclass of Error class

(1) VirtualMachineError -- virtual machine error class

  • OutOfMenoryError: memory overflow error
  • StackOverflowError: stack overflow error
    (2) LinkageError -- link error class
    (3) NoClassDefNotFoundError -- the class definition did not find the error class
    (4)java. awt. Awtiror -- Graphical interface error class

Exception handling

Cause of abnormality

(1) The java virtual machine has detected abnormal execution states. These states may be caused by the following conditions

    1)Expression evaluation violated java Semantics of language, such as integer divided by 0;
    2)Load or link java Error in program;
    3)Some resource limits have been exceeded, such as using too much memory or exceeding the length of the array.

(2) The throw statement in the java program code is executed.
(3) Asynchronous exception occurs; The reason may be that the stop() method of Thread is called and there is an internal error in the java virtual machine.

How to handle exceptions

(1) Throw exception

      When the semantic rules are violated when the program is running, it will be thrown( throw)Exception, that is, an exception event is generated,
      Generate an exception object. An exception object can be java Generated by the virtual machine, that is, generated by the running method.
      The exception object contains the type of exception event, program running state and other necessary information.

(2) Catch exception

  After the exception is thrown, the exception object is submitted to the running system. The system will start from the code that generates the exception object and run along the method call stack
  Search until you find the method code containing the corresponding processing, and hand over the exception object to the method for processing. This process is called
  To catch exceptions

try... catch... finally clause

explain:
In programming, put the code that may cause exceptions in try Statement segment, using try Statement to monitor this set of code, such as
 If a problem occurs, the system will throw an exception object e,hand catch Statement processing, the processing steps are as follows:
1) catch Before executing the statement, first identify the type of exception object thrown catch Can capture, if catch Declared in statement parameters
 The exception class is the same as the exception class thrown, or it is its parent class, catch Statement can catch this exception
2)If the exception is not caught, the exception object is thrown e And catch "Exception type" defined does not match, process control will "
Down the call stack. in other words catch If method 1 cannot handle the exception, pass the exception to catch Method 2, e.g
 fruit catch Method 2 cannot handle the exception, and then pass the exception to method 3, so that the exception can be passed to the method that can handle it, such as this one
 individual try Code block followed by multiple catch The case of code blocks is called multiple capture.
3)If you know that no exception handling is found in the end catch Statement, then in finally When the clause is executed, it is called. ThreadGroup
 of unCatchException Method to terminate the current thread (that is, the thread with exception).
    public static void method01(){
        Scanner sc=new Scanner(System.in);
        try {
            int a= sc.nextInt(), b= sc.nextInt();
            int c=a/b;

            int arr[]={1};
            arr[0]=c;

            //Null pointer exception occurred
            String str=null;
            System.out.println(str.replace('c','a'));

            System.out.println(a+"/"+b+"="+c);
        }catch (ArithmeticException e){//Arithmetic exception
            System.out.println("Division operation, divisor cannot be 0");
        }catch (InputMismatchException e){
            System.out.println("Input data type error");
            System.out.println("Please re-enter");
            method01();
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println("Subscript overflow");
        }catch (Exception e){//Unable to determine what exception was caught
            e.printStackTrace();  //It is only used for TODO test, and printing exceptions
            System.out.println("An exception occurred, message:"+e.toString());
            return;//TODO
        }finally {//If there is any exception, it will run, and return can't stop it
            System.out.println("Whether there is an exception or not, it must run here");
        }
    }

throw statement

stay catch The exception object in clause is java The exception object thrown by the runtime system can also be implemented through program code. use
throw Statement can explicitly throw an exception object, throw It's a java The keyword of the language used to inform the compiler of the message to be sent here
 Give birth to an exception, throw Followed by a newly created exception class object to indicate the name and type of the exception.

Statement format:
<throw><new><Exception object name ()>
explain:
During program execution throw End at statement, turn to try...catch Find an exception handling method and do not execute it again throw The following statement.
public class Test03 {
    public static void main(String[] args) {
        try {
            method01();
        }catch (NullPointerException e){
            System.out.println("Capture one again:" + e);
        }
    }

    public static void method01(){
        try {
            throw new NullPointerException("Null pointer exception");

        }catch (NullPointerException e){
            System.out.println("\n stay method Method" + e);
            throw e;
        }
    }
}

throws clause

throws It is used to declare various exceptions that may be thrown in a method, and explain that the method will throw exceptions but will not catch exceptions
1)Throw an exception and let other methods handle it
2) Declaration of multiple exceptions
 A method declaration can throw multiple exceptions, separated by commas
3)There is a way to throw an exception, which is handled by the dating system
 Format:
<return type><Method name><([parameter])><throws><Exception type>{ }
    //Custom exceptions cannot be handled by themselves and can only be thrown
    public static void method03 (String sex)throws Exception{
        //When sex is neither male nor female, it is considered abnormal
        if(!(sex.equals("male")||sex.equals("female"))){
            throw new Exception("Gender neither male nor female");
        }
    }
    public static void method04(String sex)throws SexException{
        if(!(sex.equals("male")||sex.equals("female"))){
            throw new SexException("Gender neither male nor female");
        }
    }
class SexException extends Exception{
    public SexException(String msg) {
        super(msg);
    }
}

finally statement

Whether or not an exception occurs, finally Statements are executed

Exception checking at compile time

1)Detectable and non detectable classes
 The undetectable exception class is RuntimeException And its subclasses, Error And its subclasses, and other exception classes are detectable classes.

2)Handling of detectable exceptions
 adopt try...catch To capture, or through throws Throw and leave it to the caller

3)Handling of undetectable exceptions (runtime exception classes)
The compiler does not detect undetectable exceptions, and the interpreter will give an exception report to the program with exceptions when executing the program

Create your own exception class

Custom exception class

Custom exception types are from Exception Class, which can be created by inheritance
 Format:
 <class><Custom exception name><extends><Exception>{...}
be careful:
 1) All exceptions must be Throwable Subclass of
 2)If it is a checking exception class, it inherits Exception
 3) If it is a runtime exception class, inherit RuntimeException class
class SexException extends Exception{
    public SexException(String msg) {
        super(msg);
    }
}

Principle of using exceptions

1)Used in the current method declaration try...catch Statement.
2)The method in a method that overrides it must throw the same exception or subclass of the exception.
3)If multiple exceptions are thrown in the parent class, the override method must throw a subset of those exceptions and cannot throw new exceptions

New features of exception handling

try... with... Resources statement

 yes java7 A new exception handling mechanism, which can be easily closed in try...catch Statement. Resources here refer to objects that must be closed after the program is completed,
 Format:
 try(Resource res = ...){
 ....//Use resource object res
 };
 1)The resources must be realized java.lang.AutoCloseable Interface, which has only one abstract method:
 void close() throws Exception
 2)Can contain catch and finally Clause. catch and finally Clause will be try...catch...resources Clause is called after the open resource is closed
    public static void method02() throws IOException {
        System.out.println("Here is the use try...with...resources Examples of\n");
        try (Scanner sc = new Scanner(Paths.get("F:/file/005.txt"))){
            while (sc.hasNext()){
                System.out.println(sc.next());
            }
        }
    }


Catch multiple exceptions

java7 Can be in the same catch Clause to catch multiple exception types between multiple exception classes“ | " separate
    public static void main(String[] args) {
        try {
//            method01();
            method02();
        }catch (NullPointerException | IOException e){
            System.out.println("Capture one again:" + e);
        }
    }

explain:
When catching multiple types of exceptions, the exception variable has an implicit final Modifier, so the program cannot reassign the exception variable. Catch multiple exceptions
 It can not only reduce code redundancy and make the code more concise, but also improve efficiency.

Exception classes that simply handle reflection methods

java7 Introduce a new parent class in ReflectiveOperationException,It is used to catch all other sub exceptions through one exception
 Related exceptions provide a public parent.
 Format:
 catch(ReflectiveOperetionException e){...}
    public static void method03()throws Exception{
        try {
            Class c = Class.forName("chapter6.User");  //Gets the object of the User class
            Method method = c.getMethod("method03"); //Get method03() method
            method.invoke(c.newInstance());  //Call method03()
        }catch (ReflectiveOperationException ex){
            System.out.println("An exception occurred in the program");
            ex.printStackTrace();
        }
    }

Topics: Java