Python错误处理:异常捕获和自定义异常示例?

原创 超、凢脫俗 2025-01-20 16:27 47阅读 0赞

在Python中,异常处理允许你在代码中检测到错误,并决定如何或是否应该继续执行。主要的异常处理机制包括try/except块,finally块,以及自定义异常。

  1. try/except块:
    1. try:
    2. # 这里是可能会出错的代码
    3. num = 1 / 0
    4. except ZeroDivisionError:
    5. print("Cannot divide by zero!")
  2. finally块:
    1. try:
    2. file = open("test.txt", "r")
    3. content = file.read()
    4. file.close()
    5. except FileNotFoundError:
    6. print("File not found.")
    7. finally:
    8. print("This will always be executed, regardless of errors in the try/except block.")
  3. 自定义异常:
    ```python
    class MyCustomError(Exception):
    def init(self, message):
    1. 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`块捕获和处理异常。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,47人围观)

还没有评论,来说两句吧...

相关阅读