Runtime exceptions and compile time exceptions in java?

In Java, exceptions are divided into two types: runtime exceptions (Runtime Exceptions) and compile-time exceptions (Checked Exceptions).

1. Compile-time exceptions (Checked Exceptions):
Compile-time exceptions refer to exceptions that may occur in Java code. The compiler is forced to handle these exceptions or declare them to be thrown when compiling the code. If these exceptions are not handled or thrown, the compiler will report an error. Compile-time exceptions usually involve operations on external resources, such as file I/O, network connections, etc.

Characteristics of compile-time exceptions:
- Exceptions must be handled or caught through try-catch statement blocks, otherwise compilation errors will result.
- You can use the throws keyword in the method signature to declare thrown exceptions.

示例:
```java
import java.io.FileReader;
import java.io.FileNotFoundException;

public class Main {
   public static void main(String[] args) {
      try {
         FileReader file = new FileReader("file.txt"); // 可能抛出FileNotFoundException异常
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      }
   }
}
```

2. Runtime Exceptions: Runtime
exceptions refer to exceptions that may occur during program running. These exceptions do not need to be forced to be handled or declared to be thrown. Unlike compile-time exceptions, run-time exceptions are usually caused by developer errors, logic problems, or exceptions in the running environment, such as array out-of-bounds, null pointer references, etc. Runtime exceptions are thrown dynamically while the program is running and therefore can be handled selectively.

Characteristics of runtime exceptions:
- Exception handling can be selectively performed.
- It is not necessary to declare an exception in the method signature.
- If these exceptions are not handled, the program will throw an exception and terminate.

Example:
```java
public class Main {    public static void main(String[] args) {       int num1 = 10;       int num2 = 0;       try {          int result = num1 / num2; // ArithmeticException may be thrown          System.out .println(result);       } catch (ArithmeticException e) {          e.printStackTrace();       }    } } ```











Summary:
Compile-time exceptions are exceptions that are detected during the compilation phase and need to be handled or declared to be thrown. Runtime exceptions are exceptions that are thrown dynamically while the program is running and can be handled selectively. Whether it is a compile-time exception or a run-time exception, it belongs to the exception system in Java. By correctly handling exceptions, the stability and reliability of the code can be improved.

Guess you like

Origin blog.csdn.net/qq_45635347/article/details/132483551