Java Basics - exceptions

Posted by yodasan000 on Mon, 07 Mar 2022 11:48:19 +0100

Exception

Basic concepts

In the Java language, abnormal conditions occurring in program execution are called "exceptions". (syntax and logic errors in the development process are not exceptions)

Abnormal events during execution can be divided into two categories:

  1. Error: a serious problem that the Java virtual machine cannot solve. Such as: JVM system internal error, resource exhaustion, stack overflow and other serious situations. Error is a serious error and the program will crash.
  2. Exception: other general problems caused by programming errors or accidental external factors can be handled with targeted code. For example, null pointer access, trying to read non-existent files, network connection interruption, etc., exceptions are divided into two categories: runtime exceptions [exceptions that occur when the program is running] and compile time exceptions [exceptions checked by the compiler at compile time].

Anomaly system diagram

  1. Exceptions are divided into two categories: runtime exceptions and compile time exceptions.
  2. The compiler cannot detect the runtime exception. It generally refers to the logic error of compilation, which is an exception that programmers should avoid. java.lang.RuntimeException class and its subclasses are runtime exceptions.
  3. For runtime exceptions, you can not handle them, because such exceptions are very common. If they are fully handled, it may affect the readability and running efficiency of the program.
  4. Compile time exceptions are exceptions that the compiler requires to handle.

Common runtime exceptions

  • Null pointerexception null pointer exception
When an application tries to use an object where it is needed null This exception is thrown when.

  • ArithmeticException mathematical operation exception

This exception is thrown when an abnormal operation condition occurs.

  • ArrayIndexOutOfException array index out of bounds exception

An exception thrown when accessing an array with an illegal index. If the index is negative or greater than or equal to the array size, the index is illegal.

  • ClassCastException type conversion exception

This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance.

  • NumberFormatException number format is incorrect exception

An exception is thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.

Compile time exception

Compilation exception refers to the exception that must be handled during compilation, otherwise the code cannot be compiled.

  1. When sqlexecution operates the database, exceptions may occur in the query table.
  2. IOException is an exception that occurs when a file is manipulated.
  3. FileNotFoundException operation is an exception that occurs when a file does not exist.
  4. An exception occurs when ClassNotFoundException loads a class and the class does not exist.
  5. EOFExecption operation file, exception occurs at the end of the file.
  6. Iiiegalargumentexception parameter exception

exception handling

Exception handling is the way to handle exceptions when exceptions occur.

Exception handling method:

  1. Try catch finally programmers catch exceptions in the code and handle them by themselves.
  2. Throws throws the exception that occurs and gives it to the caller (method) for processing. The top-level handler is the JVM.

Try catch exception handling

java provides try and catch blocks to handle exceptions. Try blocks are used to contain code that may make mistakes. The catch block uses and to handle exceptions that occur in the try block. You can have multiple try in the program according to your needs Catch block.

try{

//Suspicious code

//Generate the exception object corresponding to the exception and pass it to the catch block

}catch (exception){

//Handling of exceptions

}

//If there is no finally, the syntax can be passed

 

Try catch handling exceptions - precautions

  1. If an exception occurs, the code after the exception will not be executed and directly enters the catch block.
  2. If the exception does not occur, the code blocks of try will be executed in sequence and will not enter the catch.
  3. If you want to execute a piece of code regardless of whether an exception occurs (such as closing a connection, releasing resources, etc.), use finally {}
  4. There can be multiple catch statements to catch different exceptions (for different business processing). It is required that the parent Exception is in the rear and the child Exception is in the front. For example (Exception is in the rear and NullPointerException is in the front). If an Exception occurs, only one catch will be matched.
  5. It can be used with try finally. This usage is equivalent to not catching exceptions, so the program will crash / exit directly. The application scenario is to execute a piece of code. Whether an exception occurs or not, a certain business logic must be executed.
  6. After catch catches an exception, it will just jump out of the try block and no longer execute the code segment after the exception in the try code block. However, after the capture is completed, you can continue to execute the code after the catch block.
package com.study.srv.demo9;

import com.study.srv.demo4.Person;

/**
 * @author Wen Xiansen
 * @version 1.0
 * @date 2022/2/28 18:18
 */
public class Demo01 {
    public static void main(String[] args) {
        try {
            int a=3;
            int b=0;
            System.out.println(a/b);
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("Final execution");
        }
        System.out.println("If this sentence is printed, it means that the program does not crash when it catches exceptions");
    }
}

package com.study.srv.demo9;

import com.study.srv.demo4.Person;

/**
 * @author Wen Xiansen
 * @version 1.0
 * @date 2022/2/28 18:18
 */
public class Demo01 {
    public static void main(String[] args) {
        //There is no catch block, only try finally
        try {
            int a=3;
            int b=0;
            System.out.println(a/b);
        } finally {
            System.out.println("No, catch Block, the program will not catch exceptions and should crash");
        }
        System.out.println("If this sentence is printed, it means that the program does not crash when it catches exceptions");

    }
}

 

Try catch finally execution sequence summary

  1. If there is no exception, execute all the statements in the try block instead of the statements in the catch block. If there is finally, execute the statements in fianlly.
  2. If an exception occurs, the remaining statements in the try block will not be executed after the exception occurs in the try block. The statements in the catch block will be executed. If finally, the statements in the fianlly block still need to be executed.
package com.study.srv.demo9;

import com.study.srv.demo4.Person;

/**
 * @author Wen Xiansen
 * @version 1.0
 * @date 2022/2/28 18:18
 */
public class Demo01 {
    public static void main(String[] args) {
        System.out.println(fly());
    }
    public static int fly(){
        try {
            String[] name=new String[3];
            if (name[1].equals("tom")){//Although there is an array, the array at this time is null, so a NullPointerException exception will appear during judgment.
                System.out.println(name[1]);
            }else {
                name[3]="jack";
            }
            return 1;
        } catch (ArrayIndexOutOfBoundsException e) {
            return 2;
        } catch (NullPointerException e){//Although a NullPointerException exception occurred, 3 was returned
            return 3;
        }finally {//But in the finally block, it will be executed, so in the end, it actually returns 4
            return 4;
        }
    }
}

 

throws exception handling

  1. If a method (when the statement in is executed) may generate some kind of exception, but it is not sure how to deal with this exception, the method should explicitly declare to throw an exception, indicating that the method will not deal with these exceptions, but the caller of the method is responsible for dealing with them.
  2. In the method declaration, the throw statement can be used to declare the list of exceptions thrown. The exception type after throws can be the exception type generated in the method or its parent class.

Handling exceptions in throws mode - precautions

  1. For compilation exceptions, the program must handle them, such as try catch or throws
  2. For runtime exceptions, if they are not handled in the program, they are handled by throws by default
  3. When the subclass overrides the method of the parent class, the provisions on throwing exceptions: for the method overridden by the subclass, the exception type thrown by the subclass is either consistent with the exception thrown by the parent class, or it is a subtype of the exception type thrown by the parent class.
  4. In the process of throws, if there is a method try catch, it is equivalent to handling exceptions, and throws is not required.

Custom exception

When there are some "errors" in the program, but the error information is not described in the Throwable subclass, you can design your own exception class to describe the error information.

Custom exception steps:

  1. Define class: custom Exception class name (written by the programmer) inherits Exception or RuntimeException
  2. If you inherit Exception, it is a compilation Exception.
  3. If you inherit RuntimeException, it belongs to runtime exception (generally inherited RuntimeException).
package com.study.srv.demo9;

/**
 * @author Wen Xiansen
 * @version 1.0
 * @date 2022/3/4 10:36
 */
public class Demo04 {
    //Because it is an inherited runtime exception, it is handled in the throw mode by default
    public static void main(String[] args) {
        int age=10;
        if (!(age>=18&&age<=60)){
            throw new AgeException("The age needs to be between 18 and 60");
        }
        System.out.println("Normal age range");
    }
}
//In general, custom exceptions are inherited from RuntimeException
//That is, making custom exceptions run-time exceptions has the advantage that the default display mechanism can be used
class AgeException extends RuntimeException{
    public AgeException(String message){
        super(message);
    }
}

 

The difference between throw and throw

significancepositionWhat follows
throwsA way of exception handlingMethod declarationException type
throwKeywords for manually generating exception objectsMethod bodyException object
package com.study.srv.demo9;

/**
 * @author Wen Xiansen
 * @version 1.0
 * @date 2022/3/4 11:25
 */
public class Demo05 {
    public static void main(String[] args) {
        try {
            ReturnException.methodA();//1. Call method A
        } catch (Exception e) {
            System.out.println(e.getMessage());//5. Print out the returned exception information at this time. Print "manufacturing exception"
        }
        ReturnException.methodB();//6. Because the catch block catches an exception, the program continues to execute and calls method B
    }
}
class ReturnException{
    static void methodA(){
        try {
            System.out.println("Enter to method A");//2. Print "enter method A" after entering method A
            throw new RuntimeException("Manufacturing exception");//3. An exception occurs and the exception information is returned. However, due to the finally block, the finally block code must be executed first before the exception information can be returned.
        } finally {
            System.out.println("use A Methodical finally");//4. Execute the finally block and print "finally with method A"
        }
    }
    static void methodB(){
        try {
            System.out.println("Enter to method B");//7. Enter method B and print "enter method B"
            return;
        } finally {
            System.out.println("use B Methodical finally");//8. Execute the finally block and print "finally with method B"
        }
    }
}

 

Topics: Java