Python中异常处理:常见错误捕获示例
在Python编程中,异常处理是一种机制,用于在程序执行过程中遇到错误时进行适当的处理。以下是一些常见的错误捕获示例:
- 使用try/except块捕捉特定错误:
```python
def divide(a, b):
try:
except ZeroDivisionError:return a / b
print("Can't divide by zero!")
return None
result = divide(10, 2)
print(result) # Output: 5.0
2. **使用except所有错误**:
```python
def perform_operation(a, b):
try:
result = a + b
print("Operation performed successfully.")
return result
except Exception as e:
print("An error occurred:", str(e)))
return None
result = perform_operation(5, "2")
print(result) # Output: An error occurred: can't convert 'str' to 'int'
- 使用finally块确保某项操作始终执行:
```python
def write_to_file(file_name, content):
try:
except Exception as e:with open(file_name, 'w') as file:
file.write(content)
print(f"Content written to '{file_name}' successfully.")
return True
print("An error occurred:", str(e)))
finally:
print("File operation cleanup performed.")
return False
result = write_to_file(‘test.txt’, “Hello, World!”)
print(result) # Output: Content written to ‘test.txt’ successfully.
```
通过这些示例,你可以理解如何在Python中使用异常处理来捕获和处理错误。
还没有评论,来说两句吧...