Home > Java > javaTutorial > body text

How to solve the classification problem of java exception handling

王林
Release: 2023-05-19 15:04:06
forward
1005 people have browsed it

1. Description

(1) For runtime exceptions, they can be processed without explicit processing

(2) For compile-time exceptions , must be processed explicitly

2. Method 1:

try{
// 可能出现异常的代码
}catch(Exption1 e1){
// 处理方式一
}catch(Exption2 e2){
// 处理方式二
}finally{
// 一定要执行的代码
}
Copy after login

Note:

(1) Declared in try Variables, similar to local variables, cannot be called except for try{} statements

(2) The inside of the catch statement handles exception objects: e.getMessage(); e.printStackTrace()

(3) Multiple catch statements can be used. The exception class object thrown in try matches the type of exception class in catch from top to bottom. Once satisfied, the code in catch will be executed. After execution, it will jump out. Multiple catch statements

(4) If the exception is handled, then the subsequent code continues to execute

(5) If the multiple exception types in the catch are in a "parallel" relationship, then the order Both before and after can be used. If multiple exception types in the catch are in an "include" relationship, the subclass must be placed before the parent class for processing. Otherwise, an error will be reported

(6) finally is optional

(7) finally stores code that will definitely be executed regardless of whether there are still unhandled exceptions in try or catch, and whether there is a return statement

(8) try-catch is possible Nested

3. Method 2:

(1) At the declaration of the method, explicitly throw the type of the exception object

(2) Format, such as:

public static void method() throws Exception{}
Copy after login

(3) When an exception occurs inside this method, an object of the exception class will be thrown to the caller of the method

(4) Exception objects can be thrown upward layer by layer until main. Of course, during the upward throwing process, it can be processed through try-catch-finally

The above is the detailed content of How to solve the classification problem of java exception handling. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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