Java interview questions - exceptions and errors

Tip: Explain what exceptions and errors are in Java, and what's the difference between them?


Preface

提示:这里可以添加本文要记录的大概内容:

In the Java programming language, both exceptions and errors are problems that can occur when a program is running, but there are some important differences between them.


提示:以下是本篇文章正文内容,下面案例可供参考

By definition:

Exception Exception:

Exceptions are problems that occur while the program is running. They are usually predictable and can be dealt with. For example, trying to open a file that does not exist, or accessing an element outside the range of an array are operations that may cause exceptions. In Java, exceptions can be divided into two major categories, namely checked exceptions (Checked Exceptions) and unchecked exceptions (Unchecked Exceptions). Checked exceptions are exceptions that the compiler forces you to handle, such as IOException, SQLException, etc. Unchecked exceptions are usually caused by program errors, such as NullPointerException, IndexOutOfBoundsException, etc.

Error Error:

Errors are problems that occur in the Java Runtime Environment (JRE). Such problems are usually not foreseeable and cannot be handled by the application. For example, a Java Virtual Machine (JVM) crash or memory exhaustion is an error. Common error types include OutOfMemoryError, StackOverflowError, etc.

From the perspective of processing method:

For exceptions, we can catch and handle them by writing code. For example, use a try-catch statement block to catch and handle exceptions that may occur.

And for errors, we usually can't handle them in the program. For example, if the JVM crashes or runs out of memory, the program often can't do anything. We can only record error messages and take appropriate measures to avoid program crashes.

Overall, understanding and correctly handling exceptions and errors in Java is important for writing robust, reliable code.

Exceptions are usually foreseeable, while errors are usually unforeseen. That is to say, we can avoid exceptions through appropriate code design and logic, but we usually cannot avoid errors.
Exceptions can usually be handled, but errors usually cannot. When an exception occurs, we can use the try-catch statement to catch and handle the exception. However, when an error occurs, we can usually only log the error and take appropriate measures to avoid program crashes.
Exceptions are part of the program, while errors are problems outside the program. In other words, exceptions are part of the program and can be designed to be part of the program. An error is a problem outside the program. It may be caused by the environment, hardware, operating system, or other factors.
Let us now understand exceptions and errors with some code examples:

// 示例1:处理异常  
import java.io.*;  
  
public class ExceptionExample {
    
      
    public static void main(String[] args) {
    
      
        try {
    
      
            File file = new File("non_existent_file.txt");  
            FileReader fr = new FileReader(file);  
        } catch (FileNotFoundException e) {
    
      
            e.printStackTrace();  
        }  
    }  
}

In this example, we are trying to open a file that does not exist, an operation that may throw an exception. We use the try-catch statement to catch and handle this exception.

// 示例2:处理错误  
public class ErrorExample {
    
      
    public static void main(String[] args) {
    
      
        try {
    
      
            int[] arr = new int[5];  
            System.out.println(arr[10]);  
        } catch (ArrayIndexOutOfBoundsException e) {
    
      
            e.printStackTrace();  
        }  
    }  
}

In this example, we are trying to access an array element that does not exist, an operation that can lead to errors. We use try-catch statements to catch and handle this error. However, please note that although we can catch and handle this error, we cannot prevent it from happening. This is because errors by their nature are unforeseeable and unmanageable.

Summarize

Exceptions and errors in Java are both problems that can occur when a program is running, but there are important differences between them. Understanding these differences and knowing how to handle them appropriately is important to writing robust code.

Exceptions are usually foreseeable and can be handled, and are part of the program; errors are usually unforeseen, cannot be handled, and are problems outside the program. When handling exceptions and errors, we need to take appropriate measures according to the specific situation to ensure the robustness, readability and stability of the program.

⭐️ Good book recommendations

Insert image description here
Tsinghua News Agency [Autumn Reading Plan] Get coupons and enjoy discounts immediately

IT Good Book 5 fold plus 10 yuan no-threshold coupon: click me!

Event time: September 4th to September 17th, first come first served, come and grab it quickly

Recommended in this issue: Java from entry to proficiency (7th edition)
JD.com link , Dangdang link
Insert image description here

Guess you like

Origin blog.csdn.net/rej177/article/details/132911539