Python错误处理:异常捕获和自定义异常示例?
在Python中,异常处理允许你在代码中检测到错误,并决定如何或是否应该继续执行。主要的异常处理机制包括try/except
块,finally
块,以及自定义异常。
try/except
块:try:
# 这里是可能会出错的代码
num = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally
块:try:
file = open("test.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("File not found.")
finally:
print("This will always be executed, regardless of errors in the try/except block.")
- 自定义异常:
```python
class MyCustomError(Exception):
def init(self, message):self.message = message
try:
raise MyCustomError(“This is a custom error message.”))
except MyCustomError as e:
print(f”Error occurred: {e.message}.”)``
以上示例展示了如何在Python中使用
try/except`块捕获和处理异常。
还没有评论,来说两句吧...