当我无法处理异常时,为什么退出代码为零(“良好”)?

时间:2019-10-25 13:25:48

标签: python python-3.x

请考虑以下代码段以及从控制台获得的打印输出:

片段1

表现 精细 。一切都是笨拙的。

代码

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

摘要2

也表现得 很好 。一切都是笨拙的。

代码

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

摘要3

我不明白为什么以下情况不会导致未处理的异常打印到控制台:

代码

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

2 个答案:

答案 0 :(得分:11)

finally块返回将丢弃该异常。该函数无法返回引发异常,并且您告诉它要返回它。

将引发异常,但是在退出try语句之前,需要运行finally块。您的finally块显示“无论您做什么,我都想回来”。因此,该异常将被丢弃。

Similary,如果您正在从try返回,而finally块引发了异常,则返回值将被丢弃。

请参见Python文档中的Defining Clean-up Actions

  
      
  • 如果在执行try子句期间发生异常,则可以通过except子句处理该异常。如果except子句未处理该异常,则在执行finally子句后将重新引发该异常。
      ...
  •   
  • 如果finally子句包含return语句,则finally子句的return语句将在try子句中的return语句之前执行,而不是执行。
  •   

答案 1 :(得分:-2)

原因是您的除外声明。

>>> type("", (Exception,), dict())
<class '__main__.'>

由于“ ValueError”不是该类型的异常,因此不会捕获该异常,而只会进入finally语句。 将except语句更改为:

except ValueError as e:
    pass
# or this:
except Exception as e:
    pass