I. What Is Exception Handling?
Exception handling is a control mechanism used to detect, propagate, and handle abnormal conditions during program execution.
While a program is running, it may encounter various situations that cannot be completed as expected:
- The file does not exist or access is denied.
- A network connection fails or a request times out.
- An array index is out of bounds or a null pointer is accessed.
- A type conversion fails.
- A database transaction fails to execute.
- Memory allocation fails.
- User input does not meet expectations.
If a program only follows the normal execution path, it cannot reliably handle these situations.
Exception handling mechanisms allow a program to separate normal business logic from exception handling logic. When an exception occurs, the runtime system searches for an appropriate handling location based on the exception type and call stack.
1. Difference Between Exceptions and Errors
Exceptions and errors are often used interchangeably in everyday development, but their technical meanings are not exactly the same.
| Concept | Meaning | Example |
|---|---|---|
| Exception | An abnormal condition that occurs during program execution | File does not exist, network timeout |
| Error | A broader failure state that may arise from a program defect or the runtime environment | Out of memory, system resources exhausted |
| Bug | An error in program design or implementation | Incorrect array index calculation |
| Failure | The program or system fails to complete the expected function | Request processing fails, service unavailable |
Different languages classify Exception and Error differently.
For example:
- Java defines both
ExceptionandErroras subclasses ofThrowable. - Python uses
BaseExceptionas the root type of its exception hierarchy. - JavaScript uses
Errorand its derived types to represent most exceptions. - Go does not use a traditional exception system; it mainly represents expected failures by returning
error.
Therefore, the specific meanings of exception and error must be understood in the context of a language's exception model.
2. What Problems Does Exception Handling Solve?
Exception handling mainly solves three problems:
- Error detection: Identify abnormal conditions that occur during program execution.
- Error propagation: Pass problems that the current layer cannot handle to the caller at the upper layer.
- Error recovery: Handle the exception at an appropriate location so that the program can continue executing or exit safely.
Typical handling process:
flowchart TD
A["Normal program execution"] --> B["Perform an operation"]
B --> C{"Exception occurred?"}
C -->|"No"| D["Continue normal execution"]
C -->|"Yes"| E["Create or throw an exception"]
E --> F["Find an exception handler"]
F --> G{"Handler found?"}
G -->|"Yes"| H["Execute exception handling logic"]
G -->|"No"| I["Continue propagating to the upper layer"]
I --> J{"Handler found?"}
J -->|"Yes"| H
J -->|"No"| K["Uncaught exception; program or thread terminates"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style I fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
II. Core Components of Exception Handling
Syntax varies between languages, but traditional exception handling mechanisms usually include the following components.
1. try: Monitor Code That May Throw Exceptions
try is used to surround code that may throw exceptions.
try:
result = 10 / 0
When the code in try executes normally, the program continues with the subsequent logic.
When an exception occurs, the program stops executing the remaining statements in the current try block and attempts to find a matching exception handler.
Note:
tryitself does not handle exceptions.tryonly marks the region of code that needs to be monitored.- Whether an exception gets handled depends on whether a matching handler exists.
2. throw / raise: explicitly throwing an exception
When a program detects some state that does not match expectations, it can explicitly throw an exception.
Different languages use different keywords:
| Language | Throwing an exception |
|---|---|
| Python | raise |
| Java | throw |
| JavaScript | throw |
| C# | throw |
| C++ | throw |
Python example:
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("金额必须大于 0")
if amount > balance:
raise ValueError("余额不足")
return balance - amount
Explicitly throwing an exception is usually meant to express that the current operation cannot be carried through.
Two cases need to be distinguished:
- Exceptions produced by the system: for example, a file fails to open, or a type conversion fails.
- Exceptions thrown explicitly by the program: for example, a business rule validation does not pass.
Explicitly throwing an exception can turn a business constraint into an unambiguous error signal.
3. catch / except: catching and handling exceptions
Catching an exception means the program takes over the handling process instead of letting the exception keep propagating to the upper layers.
Python example:
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零")
Java example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("不能除以零");
}
When catching exceptions, you should specify an explicit exception type whenever possible.
Catching all exceptions indiscriminately is not recommended:
try:
process_data()
except Exception:
pass
This style hides the real error, letting the program appear to keep running while its actual state may already be incorrect.
4. finally: running cleanup logic
finally defines cleanup logic that should normally run regardless of whether an exception occurs in try.
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("文件不存在")
finally:
print("执行清理逻辑")
Common uses:
- Closing files.
- Releasing locks.
- Closing database connections.
- Releasing other external resources.
But note that finally does not mean guaranteed execution. Cases such as the process being forcibly killed, a runtime crash, or a power failure can all prevent the cleanup logic from completing.
5. else: running when no exception occurs
Some languages support an else clause, for example Python.
try:
result = 10 / 2
except ZeroDivisionError:
print("除数不能为零")
else:
print("计算成功:", result)
finally:
print("执行结束")
Execution rules:
- An exception occurs in
try: the matchingexceptruns. - No exception occurs in
try:elseruns. - Regardless of whether an exception occurs:
finallynormally runs.
else helps narrow the scope of exception catching and keeps code that should not be caught out of try.
III. The Execution Mechanism of Exception Handling
Understanding exception handling cannot stop at the syntax level; you also need to understand how exceptions propagate while the program runs.
1. Exception propagation mechanism
When an exception occurs in a function but that function does not handle it, the exception propagates up to the upper layers along the function call chain.
For example:
def read_file():
return open("data.txt", "r")
def process_data():
file = read_file()
return file.read()
def main():
try:
process_data()
except FileNotFoundError:
print("文件不存在")
Call relationship:
flowchart TD
A["main()"] --> B["process_data()"]
B --> C["read_file()"]
C --> D["Open file"]
D --> E["FileNotFoundError occurs"]
E --> F["read_file() unhandled"]
F --> G["Propagates to process_data()"]
G --> H["process_data() unhandled"]
H --> I["Propagates to main()"]
I --> J["Catches FileNotFoundError"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There is one key point to understand here:
Exception propagation is not simply returning an error message to the caller; rather, the runtime system searches the call stack for a handler that can handle the exception.
2. Call Stack and Exception Unwinding
Function calls usually form a call stack.
Each time a function is called, the runtime system maintains the corresponding call information, such as:
- Return address.
- Local variables.
- Parameter information.
- Necessary runtime state.
When an exception occurs, the runtime system needs to determine:
- Whether a matching exception handler exists at the current execution location.
- If not, whether the current function can exit.
- After exiting the current function, continue checking the calling layer above.
- Until a handler is found, or the exception cannot be caught.
This process is commonly called stack unwinding.
flowchart TD
A["Exception occurs"] --> B["Check current stack frame"]
B --> C{"Is there a matching handler?"}
C -->|"Yes"| D["Unwind to the handler location"]
C -->|"No"| E["Execute cleanup logic for current stack frame"]
E --> F["Destroy current stack frame"]
F --> G{"Are there more upper stack frames?"}
G -->|"Yes"| B
G -->|"No"| H["Exception uncaught"]
style A fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Different languages implement this differently:
- Java typically locates handlers through mechanisms such as runtime exception tables.
- C++ implements stack unwinding using exception handling tables, runtime unwinding mechanisms, and so on.
- Python handles exception propagation through the interpreter's exception state and call frame mechanism.
- JavaScript engines maintain exception-handling-related state in execution contexts.
Stack unwinding is an important foundation for understanding exception handling, especially with respect to resource release, destructor execution, and program state recovery.
3. Difference Between Exception Propagation and Return Values
Exception propagation is fundamentally different from ordinary function return values.
| Comparison dimension | Return value | Exception |
|---|---|---|
| Control flow | Returns via the normal call path | May skip intermediate call layers |
| Caller handling | Usually needs to check the return value | Taken over by a matching exception handler |
| Representation | Returns data or an error object | Throws an exception object or exceptional state |
| Use cases | Expected results and failures | Exceptional situations that require changing normal control flow |
For example:
def divide(a, b):
if b == 0:
raise ZeroDivisionError("除数不能为零")
return a / b
Versus:
def divide(a, b):
if b == 0:
return None
return a / b
The second approach uses a return value to indicate failure, but there is a problem: the caller must distinguish whether None represents a normal business result or an operation failure.
In real-world projects, you can choose exceptions, error return values, or result types based on language conventions and business semantics.
IV. Exception Classification System
Exception classification determines the scope of exception catching, handling strategies, and how the program recovers.
1. Checked Exceptions and Unchecked Exceptions
Checked exceptions and unchecked exceptions are important concepts in the Java exception system.
Checked exceptions:
The compiler requires the caller to handle them explicitly or propagate them outward via a method declaration.
public void readFile() throws IOException {
FileInputStream input = new FileInputStream("data.txt");
}
The caller needs to handle IOException or continue declaring that it is thrown outward.
Unchecked exceptions:
The compiler does not require the caller to catch or declare them.
public int divide(int a, int b) {
return a / b;
}
When b is zero, an ArithmeticException occurs, but the method does not need to declare that exception.
Java exception hierarchy:
flowchart TD
A["Throwable"] --> B["Error"]
A --> C["Exception"]
C --> D["RuntimeException"]
C --> E["Other Exception subclasses"]
D --> F["Unchecked Exception"]
E --> G["Checked Exception"]
B --> H["Generally not recommended for business code to catch"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note:
Errorusually indicates a serious runtime or environmental problem.Exceptionindicates an exceptional condition that the application can consider handling.RuntimeExceptionand its subclasses are unchecked exceptions.- Other exceptions that directly extend
Exceptionare usually checked exceptions.
Checked exceptions are a language design feature of Java, and not all languages have the same mechanism.
2. Business Exceptions and System Exceptions
In application design, exceptions are also often distinguished by business semantics.
| Type | Meaning | Example |
|---|---|---|
| Business exception | Violates business rules or business conditions | Insufficient balance, order status does not allow changes |
| System exception | Problems occur in system operation or external dependencies | Database connection failure, file read failure |
| Programming exception | Defects in program implementation | Null pointer, array out of bounds, illegal state |
For example:
class InsufficientBalanceError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError("账户余额不足")
return balance - amount
Custom business exceptions can make errors clearer to express and make it easier for upper layers to formulate different handling strategies based on the exception type.
3. Synchronous and Asynchronous Exceptions
Synchronous exceptions usually occur in the current execution flow and propagate through the current call chain.
Exceptions in asynchronous scenarios are more complex.
For example:
- Promise rejection states in JavaScript.
- Asynchronous coroutine exceptions in Python.
- Exceptional completion states in Java CompletableFuture.
- Error returns and panics in Go concurrent tasks.
Exceptions in asynchronous tasks may not necessarily be caught by an ordinary try-catch at the location where the task was created.
JavaScript example:
async function loadData() {
try {
const response = await fetch("/api/data");
return await response.json();
} catch (error) {
console.error("请求失败", error);
}
}
Here, await re-expresses the rejection state of the asynchronous operation as an exception in the current async function, so it can be caught by try-catch.
If there is no await:
async function loadData() {
try {
fetch("/api/data");
} catch (error) {
console.error(error);
}
}
Here, try-catch usually cannot catch the Promise rejection that occurs later from fetch(), because the exception is not thrown during the current synchronous execution phase.
V. Resource Management and Exception Safety
One of the most easily overlooked issues in exception handling is how to ensure that resources are correctly released after an exception occurs.
1. Why Do Exceptions Cause Resource Leaks?
Suppose an exception occurs after the program opens a file:
def process_file():
file = open("data.txt", "r")
content = file.read()
process_content(content)
file.close()
If process_content() throws an exception, the program may skip file.close() entirely.
This can cause the file handle to not be released as expected.
Similar problems can also occur with:
- Database connections.
- Network sockets.
- File descriptors.
- Thread locks.
- Memory resources.
- Transaction objects.
Therefore, resource management must account for exception paths, not just the normal execution path.
2. finally and Resource Release
A traditional solution is to use finally:
file = None
try:
file = open("data.txt", "r")
content = file.read()
process_content(content)
finally:
if file is not None:
file.close()
Even if an exception occurs in try, execution usually enters finally to perform the close operation.
However, for complex resource management, this approach tends to produce duplicated code and can easily miss cleanup logic.
3. RAII: Resource Acquisition Is Initialization
RAII (Resource Acquisition Is Initialization) is a very important resource management concept in C++.
The core principle:
The lifetime of a resource is tied to the lifetime of an object.
Resources are acquired when an object is constructed and released when the object is destroyed.
#include <fstream>
void processFile() {
std::ifstream file("data.txt");
if (!file.is_open()) {
throw std::runtime_error("文件打开失败");
}
// Process file contents
}
When processFile() returns normally, or when an exception causes stack unwinding, the local object file is destroyed, and its destructor is responsible for closing the file.
Advantages of RAII:
- No need to manually release resources on every exit path.
- Object destruction can still be executed when an exception occurs.
- Resource management stays consistent with object lifetime.
- It can reduce the risk of resource leaks.
RAII applies not only to files but also to locks, memory, connections, and other resources that require an explicit lifetime.
4. Automatic Resource Management
Different languages provide different resource management mechanisms.
| Language | Resource management approach | Main mechanisms |
|---|---|---|
| C++ | RAII | Destructors, smart pointers, resource wrapper objects |
| Python | Context managers | with, __enter__, __exit__ |
| Java | try-with-resources | AutoCloseable, close() |
| C# | using | IDisposable, Dispose() |
| JavaScript | Explicit release and some resource management syntax | try-finally, resource management protocols |
Python example:
with open("data.txt", "r") as file:
content = file.read()
process_content(content)
Java example:
try (FileInputStream input =
new FileInputStream("data.txt")) {
// Process file contents
} catch (IOException e) {
e.printStackTrace();
}
The common goal of these mechanisms is to bind resource release to scope or object lifetime, reducing the complexity of resource management along exception paths.