解析:Python中异常处理机制的案例应用
在Python编程中,异常处理机制是一种应对程序运行中可能出现错误情况的方法。以下是一些案例应用:
- try/except循环:
```python
def divide(a, b):
try:
except ZeroDivisionError:result = a / b
print(f"Result: {result}")
print("Error: Division by zero is not allowed.")
divide(4, 2) # Normal division
divide(4, 0) # Division by zero error handling
2. **finally**块:
```python
def open_file(path):
try:
with open(path, 'r') as file:
print("File content:")
for line in file:
print(line.strip())
finally:
if "file" in locals():
file.close()
open_file('test.txt')
- 自定义异常:
```python
class CustomError(Exception):
def init(self, message):super().__init__(message)
self.message = message
def complex_cal(c1, c2):
try:
if abs(c1) > 10 or abs(c2) > 10:
raise CustomError(“Invalid input values.”)
result = (c1 + c2) / 2
return result
except CustomError as e:
print(e.message)
return None
result = complex_cal(5, -3)
if result is not None:
print(f”Result: {result}”)
```
以上就是Python中异常处理机制的一些案例应用。
还没有评论,来说两句吧...