考虑以下代码片段以及从控制台获得的打印输出:
表现还好。一切都是卑鄙的。
try:
raise ValueError()
finally:
print(3)
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 5, in <module>
raise ValueError()
ValueError
3
也表现得很好。一切都是卑鄙的。
try:
raise ValueError()
except type("", (Exception,), dict()):
print("this is not supposed to print")
finally:
print(3)
3
Traceback (most recent call last):
File "D:/FILE_MGMT_PYTHON/fbzdfbhedrh.py", line 14, in <module>
raise ValueError()
ValueError
我不明白为什么以下情况不会导致未处理的异常打印到控制台:
def e():
try:
raise ValueError()
x = y + z
L = [1, 2, 3]
print(L[9999999999999999999999999999])
except type("", (Exception,), dict()) as exc:
print("this is not supposed to print")
return "strawberries " + src(exc)
finally:
return "finally"
print(e())
finally
Process finished with exit code 0
------------------
System Information
------------------
Time of this report: 10/25/2019, 07:22:01
Machine name: DESKTOP-U5M46TJ
Machine Id: {403D9006-3BF1-4C4B-AAF5-2AD795E00738}
Operating System: Windows 10 Pro 64-bit (10.0, Build 18362) (18362.19h1_release.190318-1202)
Language: English (Regional Setting: English)
System Manufacturer: System manufacturer
System Model: System Product Name
BIOS: BIOS Date: 10/31/12 20:41:07 Ver: 36.02 (type: BIOS)
Processor: Intel(R) Core(TM) i5-2500K CPU @ 3.30GHz (4 CPUs), ~3.3GHz
Memory: 4096MB RAM
Available OS Memory: 4064MB RAM
Page File: 12606MB used, 3744MB available
Windows Dir: C:\Windows
DirectX Version: DirectX 12
DX Setup Parameters: Not found
User DPI Setting: 96 DPI (100 percent)
System DPI Setting: 144 DPI (150 percent)
DWM DPI Scaling: UnKnown
Miracast: Available, with HDCP
Microsoft Graphics Hybrid: Not Supported
DirectX Database Version: Unknown
DxDiag Version: 10.00.18362.0387 64bit Unicode
------------------
IDE Information
------------------
PyCharm 2019.1.3 (Community Edition)
Build #PC-191.7479.30, built on May 29, 2019
JRE: 11.0.2+9-b159.60 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
------------------
Python Information
------------------
print(sys.version)
print(sys.version_info)
print(sys.hexversion)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
50856176
从finally
块返回将丢弃该异常。该函数无法返回并引发异常,而您是在告诉它希望它返回。
将引发异常,但是在try
退出该语句之前,finally
需要运行该块。您的finally
标语栏上写着“不管您以为自己在做什么,我都想回来”。因此,该异常将被丢弃。
类似地,如果您从某个块返回try
,并且该finally
块引发异常,则返回值将被丢弃。
请参阅Python文档中的定义清理操作:
- 如果在执行该
try
子句期间发生异常,则该异常可以由except
子句处理。如果该异常不是由except
子句处理的,finally
则在执行该子句后将重新引发该异常。
...- 如果
finally
子句包含return语句,则该finally
子句的return语句将在子句中的return语句之前执行,而不是执行try
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句