Home > Java > javaTutorial > body text

Exception handling mechanism in Java

WBOY
Release: 2023-06-09 09:37:14
Original
2006 people have browsed it

Java is a beautiful and easy-to-read programming language, but errors will inevitably occur during the development process. In order to solve these errors, Java introduced an exception handling mechanism. This mechanism allows programmers to detect problems and take appropriate action while the program is running. This article will discuss the exception handling mechanism in Java, including how to throw, catch and handle exceptions.

What is the exception?

Exception is an event that indicates that an error occurred during program execution. For example, division by zero, a null pointer reference, or invalid input may occur. In Java, an exception refers to a problem encountered by a program during execution, which affects the normal execution of the program and causes the program to terminate abnormally.

Exception classification in Java

Exceptions in Java can be classified into two types: checked exceptions and unchecked exceptions.

  • Checked exceptions: are those exceptions that must be checked at compile time. If such an exception may be thrown in the code, it must be handled explicitly. For example, IOException and SqlException are checked exceptions.
  • Unchecked exceptions: are those exceptions that cannot be caught during code compilation. This exception is usually caused by programmer error or generated by the Java runtime. For example, NullPointerException and ArrayIndexOutOfBoundsException.

How to throw an exception?

When a problem is found in the program, you can use the throw statement to throw an exception.

throw new Exception("发生异常了");
Copy after login

In this example, a new Exception object is thrown. If the throw statement is followed by an object of a custom exception class, the specified exception will be thrown. The following example demonstrates how to customize an exception and use it in a program:

public class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
Copy after login

Using a custom exception in a program:

public void checkAge(int age) throws CustomException {
    if (age < 0 || age > 100) {
        throw new CustomException("年龄不在合法范围内");
    }
    //继续执行其他代码
}
Copy after login
Copy after login

In the above example, if the age is less than 0 or greater than 100, A CustomException is thrown.

How to catch exceptions?

One of the ways to handle exceptions is to "catch" it. The try-catch block in Java is used to catch exceptions.

try {
    //需要尝试执行的代码
} catch (Exception e) {
    //处理异常的代码
}
Copy after login

In this example, any code that may throw an exception can be placed in a try block. When executing the code in the try block, if an exception occurs, the program jumps to the catch block. In the catch block, the programmer can take necessary steps to handle the exception. The following is a simple Java program that demonstrates the processing of try-catch blocks.

public static void main(String[] args) {
    try {
        int i = 1/0;
    } catch (Exception e) {
        System.out.println("发生异常了:" + e);
    }
}
Copy after login

In the above example, the program will try to divide 1 by 0. Since this is not allowed, an ArithmeticException is thrown. The catch block will catch this exception and output "An exception occurred: java.lang.ArithmeticException: / by zero" on the console.

How to handle exceptions?

One way to handle exceptions is to throw them directly from the method. This will usually be caught and handled by the caller. Another way to handle exceptions is to use a method with a throws clause to specify the exceptions that need to be handled. Here is an example:

public void checkAge(int age) throws CustomException {
    if (age < 0 || age > 100) {
        throw new CustomException("年龄不在合法范围内");
    }
    //继续执行其他代码
}
Copy after login
Copy after login

The throws clause specified after the method signature tells the caller that a checked exception must be caught or thrown. If the caller does not handle this exception, the program will terminate and output the exception message.

Another way to handle exceptions is to use a finally block. The code in the finally block is executed after the try and catch blocks and will be executed regardless of whether an exception occurs.

try {
    //需要尝试执行的代码
} catch (Exception e) {
    //处理异常的代码
} finally {
    //无论是否发生异常都会执行的代码
}
Copy after login

An example of using a finally block is to close an open file or network resource. Since these resources are limited in Java, you need to remember to close them to release them.

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("文件名"));
    //对文件执行一些操作
} catch (Exception e) {
    //处理异常的代码
} finally {
    try {
        if (reader != null) {
            reader.close();
            reader = null;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Copy after login

In this example, the code in the try block opens a file and performs some operations. If an error occurs in the try block, the program jumps to the catch block and handles the exception. Regardless of whether an exception occurs in the try block, the code in the finally block closes the open file.

Conclusion

Java's exception handling mechanism enables programmers to detect errors and take appropriate measures while the program is running. This article discusses Java's exception classification, methods of throwing exceptions, catching exceptions, and handling exceptions in depth, and provides some specific examples. When writing Java code, programmers should follow best practices to ensure code stability and reliability.

The above is the detailed content of Exception handling mechanism in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template