
本文探讨了 python 中用于处理异常的各种技术,包括 try- except 块、自定义异常以及异常链接和丰富等高级功能。
python 提供了一个强大的异常处理框架,它不仅允许程序员实现防止崩溃的代码,而且还提供反馈并保持应用程序稳定性。此外,它使开发人员能够使用 try- except 块、自定义异常等结构优雅地管理错误。
– 尝试除外块
在 try- except 块中,可能引发异常的代码放在 try 块中, except 块指定发生异常时要采取的操作(python software foundation,n.d.)。
立即学习“Python免费学习笔记(深入)”;
例如:
try: result = 1 / 0except zerodivisionerror: print("cannot divide by zero.")
要在一个 try- except 块中捕获多个异常,我们可以使用带有多个 except-块的 try 块来为每种异常类型生成特定的响应。或者,我们可以使用元组通过单个异常表达式捕获多个异常。
例如:
# one try block and several except blockstry: result = 1 / 'a'except zerodivisionerror: print("cannot divide by zero.")except typeerror: print("type error occurred.")# one try block and one except tuple blocktry: # some operation result = 1 / 'a'except (zerodivisionerror, typeerror) as e: print(f"error occurred: {e}")
– else 子句
else 子句位于 try- except 块之后,如果 try 块没有引发异常,则运行该子句。
例如:
try: result = 1 / 2except zerodivisionerror: print(“cannot divide by zero.”)else: print(“division successful.”)
– 最后子句
finally 子句始终放置在 try 块或任何 except 块之后。它包含无论如何都会运行的代码,通常用于清理文件或网络连接等资源,即使引发异常也是如此。
例如:
try: result = 1 / ‘a’except zerodivisionerror: print(“cannot divide by zero.”)except typeerror: print(“type error occurred.”)else: print(“division successful.”)finally: print(“goodbye, world!”)
加薪声明
引发异常:raise 子句通过强制异常发生来引发异常,通常表示尚未满足某个条件。
例如:
if ‘a’ > 5: raise valueerror(“a must not exceed 5”)
– 异常链
您可以使用 raise 子句来链接异常。这对于向原始错误添加上下文非常有用。
例如
try: open(‘myfile.txt’)except filenotfounderror as e: raise runtimeerror(“failed to open file”) from e
– 自定义例外
您可以通过继承 exception 类或任何其他内置异常类来定义自己的异常类(mitchell,2022)。
例如:
class my_custom_ (exception): passtry: raise mycustomerror(“an error occurred”)except mycustomerror as e: print(e)
– 丰富例外
您可以使用 add_note() 方法将信息或上下文添加到异常中,将自定义消息或注释“附加”到异常对象(又名 e.
)
例如:
def divide_numbers(a, b): try: result = a / b except zerodivisionerror as e: e.add_note(“cannot divide by zero”) e.add_note(“please provide a non-zero divisor”) raisetry: num1 = 10 num2 = 0 divide_numbers(num1, num2)except zerodivisionerror as e: print(“an error occurred:”) print(str(e))
处理异常很重要,原因如下:
防止程序崩溃:未处理的异常可能会导致程序崩溃,从而导致数据丢失和糟糕的用户体验。提供有意义的错误消息:通过处理异常,您可以向用户提供信息丰富的错误消息,帮助他们了解出了什么问题以及如何修复它。允许优雅降级:异常处理使程序即使发生错误也能继续运行。
一个简单的程序错误处理示例:
##-------------------------------------------# pseudocode:# 1. define a custom exception class called customerror.# 2. create a function that raises the customerror exception # based on a condition.# 3. use a try-except block to handle the customerror exception.#-------------------------------------------# program inputs:# - num: an integer value.#-------------------------------------------# program outputs:# - custom exception message when the customerror exception is raised.# - success message when no exception is raised.#-------------------------------------------class customerror(exception): ''' a custom exception class. ''' passdef check_number(num): ''' checks if the given number is positive. :param int: num, an integer value. :raises customerror: if the number is not positive. :return: none ''' if num none: ''' the main function that demonstrates the usage of custom exceptions. ''' try: check_number(5) # valid number check_number(-2) # raises customerror except customerror as e: print(f"error: {str(e)}")#--- execute the programif __name__ == "__main__": main()
>>>Number is valid.Error: Number must be positive.
总而言之,python 提供了一个全面的异常处理框架,允许程序处理意外情况而不会突然失败。通过利用 try-except 块、自定义异常等结构以及异常链接和丰富等高级功能,开发人员可以确保他们的程序具有弹性、用户友好,并且能够优雅地处理意外情况。
参考文献:
米切尔 r(2022 年,6 月 13 日)。自定义异常。 _python 基础培训 _[视频]。领英学习。 https://www.linkedin.com/learning/python-essential-training-14898805/custom-exceptions?autoskip=true&resume=false&u=2245842
python 软件基础。 (日期不详)。 8.错误和异常。 python。 python.org.
最初于 2024 年 8 月 21 日发表于 exception handling in python – medium。
以上就是Python 中的异常处理的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1354653.html
微信扫一扫
支付宝扫一扫