try: i =1/0print("正常执行")except:print("发生异常了")#发生异常了
2.2 try/except/else
try内没有异常,else块内代码才会执行,else必须放在所有except的后面
__doc__ 是 Python 中每个对象都可能具有的属性,用于存储该对象的文档字符串
try: result =3/0except ZeroDivisionError as e:# 打印:异常名 + 异常描述print(f"1.异常名:{type(e).__name__},异常信息:{e.__doc__}")except(RuntimeError, TypeError, NameError)as e:print(f"2.异常名:{type(e).__name__},异常信息:{e}")except:print("Unexpected error")else:# try内无异常时执行的固定逻辑print("try内无异常时执行的固定逻辑")print(result)
1.异常名:ZeroDivisionError,异常信息:Second argument to a division or modulo operation was zero.
如果改为result = 3 / 1,则输出
try内无异常时执行的固定逻辑3.0
2.3 try/except/finally
无论try内是否出现异常,异常是否被捕获,finally块内语句都会执行
try: result =3/0except ZeroDivisionError as e:print(f"异常名:{type(e).__name__},异常信息:{e.__doc__}")else:print(result)finally:print("finally")
异常名:ZeroDivisionError,异常信息:Second argument to a division or modulo operation was zero.finally
如果改为result = 3 / 1,则输出
3.0finally
⚠️ finally一定会执行,所以finally中要谨慎访问可能因异常导致不存在的变量
try: result =3/0except ZeroDivisionError as e:print(f"异常名:{type(e).__name__},异常信息:{e.__doc__}")else:print(result)finally:print(result)# ❌ NameError: name 'result' is not definedprint("finally")
2.4 总结
try 执行可能产生异常的代码
except 发生异常时执行
else 没有发生异常时执行
finally 有没有异常都会执行
3.异常的产生
3.1 raise抛出
defint_add(x, y):ifisinstance(x,int)andisinstance(y,int):return x + y else:raise TypeError("参数类型错误")print(int_add(1,2))# 3print(int_add("1","2"))# TypeError: 参数类型错误
[elastic-9.x]name=Elastic repository for 9.x packagesbaseurl=https://artifacts.elastic.co/packages/9.x/yumgpgcheck=1gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearchenabled=1autorefresh=1type=rpm-md
deflazy_sum(*args):definner(): result =0for n in args: result = result + n return result #返回函数return innernum = lazy_sum(11,12)print(num)# <function lazy_sum.<locals>.inner at 0x0000023A15FD62A0>print(num())# 23print(num.__closure__)#闭包保存的变量元组 (<cell at 0x00000241568DB5E0: tuple object at 0x00000241568E8940>,)print(num.__closure__[0].cell_contents)# 闭包保存的变量 (11, 12)
例:带参数
defhello(s1):defworld(s2):return s1+' '+s2 #返回函数return worldfun = hello('hello')print(fun('world'))#hello worldprint( hello('hello')('world'))#hello world