理解Python:十大异常处理案例
在Python编程中,异常处理是一项重要的技能。它允许我们在遇到错误或异常情况时,不会程序直接中断,而是采取合适的处理策略。下面列举了十大常见的Python异常处理案例:
- 除以零(ZeroDivisionError):
try:
result = 1 / 0
except ZeroDivisionError as e:
print("Error: ", str(e))
- 文件不存在(FileNotFoundError):
filename = "non_existent_file.txt"
try:
with open(filename, 'r') as file:
content = file.read()
except FileNotFoundError as e:
print("Error: ", str(e)))
- 类型错误(TypeError):
```python
def add_string_numbers(s1, s2):
return int(s1) + float(s2)
try:
result = add_string_numbers(‘1’, ‘2.0’)
except TypeError as e:
print(“Error: “, str(e)))
4. **逻辑错误(Logic Error)**:
```python
def calculate_average(lst):
if not lst:
return "List is empty"
else:
total = sum(lst)
average = total / len(lst)
return average
try:
result = calculate_average([1, 2, 3], [4, 5, 6]])
except Exception as e:
print("Error: ", str(e)))
- 资源不足(Resource Insufficient):
def process_large_file(file_path):
try:
with open(file_path, 'r') as file:
for line in file:
# 这里处理大型文件,可能会消耗大量内存或CPU时间
pass
except Exception as e:
print("Error processing large file: ", str(e)))
- 无限循环(Infinite Loop):
```python
def infinite_loop():
while True:print("This is an infinite loop!")
infinite_loop()
7. **异常传播(Exception Propagation)**:
```python
try:
a = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {str(e)}}")
- 特定异常捕获(Specific Exception Catching):
```python
def divide_numbers(a, b):
try:
except ZeroDivisionError:result = a / b
return result
print("Error: Division by zero is not allowed.")
return None
number1 = 10
number2 = 0
result = divide_numbers(number1, number2)
if result is not None:
print(f”The division result is {result}).”)
9. **异常处理链(Exception Handling Chain)**:
```python
def calculate_total(numbers):
total = sum(numbers)
if total < 0:
raise ValueError("Total cannot be negative.")
return total
numbers = [1, 2, 3], [-4, -5, -6]]
try:
result = calculate_total(numbers)
print(f"The total is {result}).")
except ValueError as ve:
print("Error: ", str(ve)))
异常处理与程序结构(Exception Handling and Program Structure):
```python
class Calculator:
def add(self, a, b):try:
return a + b
except Exception as e:
print(f"Error in addition: {str(e)})}")
def subtract(self, a, b):
try:
return a - b
except Exception as e:
print(f"Error in subtraction: {str(e)})}")
calculator = Calculator()
numbers1 = [2, 3]
numbers2 = [-4, -5]
try:
result_addition = calculator.add(numbers1, numbers2))
print(f”Result of addition: {result_addition}).”)
result_subtraction = calculator.subtract(*numbers1, *numbers2))
print(f"Result of subtraction: {result_subtraction}).")
except Exception as e:
print(“Error: “, str(e)))
```
以上案例展示了Python中如何通过try-except块来处理和控制异常。这样可以使程序更健壮,避免因为偶然的错误导致程序崩溃。
还没有评论,来说两句吧...