[JavaSE Column 67] Talk about exceptions, learn to predict exceptions, catch exceptions, and transfer exceptions

Author homepage : Designer Xiao Zheng
Author brief introduction : 3 years of JAVA full-stack development experience, focusing on JAVA technology, system customization, remote guidance, dedicated to enterprise digital transformation, certified lecturer of CSDN College and Blue Bridge Cloud Course.
Main direction : Vue, SpringBoot, WeChat applet

This article explains the basic concepts and syntax of exceptions in Java, and gives sample codes. An exception refers to an error or abnormal situation encountered by a program during its running. When an exception occurs in the program, an exception object will be thrown, which will interrupt the normal program execution flow and transfer control to the exception handling mechanism.

insert image description here


1. What is an exception

In Java, an exception is an error or unusual condition that a program encounters while it is running .

When an exception occurs in the program, an exception object is thrown, which interrupts the normal flow of program execution and transfers control to the exception handling mechanism.

Exceptions can be divided into two types, checked exceptions and unchecked exceptions .

  1. Checked exception : A checked exception refers to an exception that the compiler requires the program to explicitly handle or declare to throw. These exceptions usually represent some expected errors or abnormal conditions in the program, which need to be handled by the programmer in the code. For example, IOException(I/O Exception) or SQLException(Database Exception), etc.
  2. Unchecked exception : An unchecked exception is an exception that the compiler does not require the program to explicitly handle or declare to throw. These exceptions are usually caused by logic errors or runtime errors in the program, which cannot be found during compilation, but are thrown when the program is running. For example, NullPointerException(Null Pointer Exception), ArrayIndexOutOfBoundsException(Array Index Out of Bounds Exception), or ArithmeticException(Arithmetic Exception), etc.

The way to handle exceptions is to use try-catchstatement blocks to catch and handle exceptions. tryWrite code that might throw an exception in the block, and handle the exception in the block catchand take appropriate action, such as outputting an error message or performing other operations.

In addition, you can also use throwsthe keyword to declare the exception that the method may throw, so that the code that calls the method must handle the exception or continue to declare the throw.

The purpose of the exception handling mechanism is to increase the robustness and fault tolerance of the program, so that the program can handle exceptions gracefully and ensure the normal operation of the program.

insert image description here


2. How the exception occurs

In Java, an exception is caused by a program encountering an error or an abnormal situation during the running process . The following are 4 44 common abnormal situations, please study carefully.

  1. Runtime errors : These errors are due to logic errors or runtime errors of the program. For example, null pointer reference, array index out of bounds, arithmetic exception, etc.
  2. Calling a method throws an exception : When calling a method, if the method declares that an exception may be thrown, and an exception occurs inside the method, the exception will be thrown. For example, exceptions that may occur when reading or writing files IOException.
  3. Explicitly throw an exceptionthrow : You can use the keyword to explicitly throw an exception in your code . This is usually an exception that is artificially thrown when an error or unusual condition is detected in the program. For example, custom exception classes and throw specific exception objects.
  4. Exceptions thrown by the JVM : There are exceptions that are automatically thrown by the Java Virtual Machine, and these exceptions usually indicate serious errors or system-level exceptions. For example, OutOfMemoryErrorindicating insufficient memory, StackOverflowErrorindicating stack overflow, etc.

In either case, when an exception occurs in the program, an exception object is created and the normal flow of execution of the program is interrupted. The exception object is thrown, and the call stack is searched for a block of code that can handle the exception.

  • If a suitable exception handler (catch block) is found, the exception is caught and handled accordingly in the handler.

  • If no suitable exception handler is found, the exception will be passed to the upper call stack until it encounters a place that can handle the exception or the program terminates.

By properly handling exceptions, the robustness and fault tolerance of the program can be increased, and the stability and reliability of the program can be guaranteed.

insert image description here


3. Types of exceptions

In Java, exceptions can be divided into three categories, checkable exceptions (, runtime exceptions and errors , please study carefully.

  1. Checkable exceptions : These exceptions are checked out at compile time, and the compiler will force them to be processed or declared to be thrown. They usually represent some expected errors or abnormal conditions in the program, which need to be handled by the programmer in the code. Common checked exceptions include: IOException, SQLException, ClassNotFoundExceptionetc.
  2. Runtime exception : These exceptions represent errors or abnormal conditions that occur during the running of the program, and are unchecked exceptions. They are usually caused by program logic errors or runtime errors that cannot be found during compilation. The compiler doesn't enforce handling or declare throws. Common runtime exceptions include: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticExceptionetc.
  3. Error : An error indicates a serious problem or a system-level exception, which is usually thrown automatically by the Java virtual machine. Generally, the error cannot be processed or recovered by the program. Common errors include: OutOfMemoryError, StackOverflowErroretc.

To handle checkable exceptions and runtime exceptions, you can use try-catchstatement blocks to catch and handle exceptions, or you can use throwskeywords to throw exceptions in method declarations. For errors, it is usually impossible to handle them effectively. The most common way is to let the program terminate .

When writing code, you should decide how to handle exceptions according to the actual situation.

For checkable exceptions, appropriate processing should be performed according to specific business needs, such as providing error information, retrying operations, or rolling back operations.

For runtime exceptions, usually caused by logic errors in the code, these exceptions should be avoided as much as possible, and appropriate boundary checks and exception handling should be performed.

For errors, which cannot be recovered through the program, errors should be avoided during the program design stage, or corresponding system-level processing should be performed when errors occur.

insert image description here


4. How to catch exceptions

In Java, try-catchexceptions can be caught using a statement block. tryThe code that may throw an exception is written in the block, and catchthe block is used to handle the caught exception. The following is a sample code, please study carefully.

public class ExceptionHandlingExample {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
    
    
            System.out.println("An arithmetic exception has occurred: " + e.getMessage());
        }
    }

    public static int divide(int num1, int num2) {
    
    
        return num1 / num2;
    }
}

In the above code, we defined a divide()method for division operation.

In main()the method, we call , which is an operation that divide(10, 0)may throw .ArithmeticException

To catch this exception, we put the operation tryin a block and catchhandle it in the block.

When the program executes to divide(10, 0), because the divisor is 0, ArithmeticExceptionan exception will be thrown.

Then, the exception will be catchcaught by the block, and the corresponding processing logic will be executed, that is, the exception information will be output: An arithmetic exception has occurred: / by zero.

Through try-catchthe statement block, we can capture and handle the exceptions that may be thrown, avoid program exceptions from causing the program to crash, and improve the robustness and fault tolerance of the program. In actual development, different types of exceptions can be caught according to specific situations, and corresponding processing operations can be performed.

insert image description here


5. Abnormal interview questions

1. What are the types of exceptions in Java?

  • Checked exception
  • runtime exception
  • mistake

2. How to catch and handle exceptions?

  • Use a try-catch block to catch exceptions, and handle exceptions in the catch block.
  • Multiple catch blocks can be used to catch different types of exceptions.
  • You can use a finally block to execute some code that needs to be executed whether or not an exception occurs.

3. What is the execution order between try-catch-finally statement blocks?

  • The code in the try block is executed first.
  • If an exception occurs in the try block, jump to the corresponding catch block for processing.
  • If no exception occurs in the try block, the catch block is skipped.
  • The code in the finally block executes whether or not an exception occurs.

4. What is the difference between the throws keyword and the throw keyword?

  • The throws keyword is used in a method declaration to indicate that the method may throw some exceptions, and the code that calls the method is responsible for handling the exceptions.
  • The throw keyword is used to explicitly throw an exception in the program, which can throw a custom exception or an existing exception type.

5. What is the difference between RuntimeException and CheckedException?

  • RuntimeExceptionIt is a runtime exception, which does not need to be explicitly declared to be thrown in the method, and it does not need to be caught.
  • CheckedExceptionIt is a checkable exception, which must be declared to be thrown or caught in the method.

6. When should you use custom exceptions?

  • When the existing Java predefined exceptions are not enough to describe a specific error or abnormal situation, you can use a custom exception to represent a specific error or abnormal situation.

6. Summary

This article explains the basic concepts and syntax of exceptions in Java, and gives sample codes. In the next blog, I will explain the capture and processing of Java exceptions.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41464123/article/details/132111370