【问题标题】:Initializing a variable after a a raise or an exceptiom in Try Except Raise在 Try except Raise 中引发或异常后初始化变量
【发布时间】:2018-10-21 05:56:36
【问题描述】:

在python中

如果我们可以在 raise 关键字之后使用初始化变量。例如

 Try:    
   func(x)  
 except ValueError  
 raise  
 data = {}

Try:    
   func(x)  
except Exception 
data = {}

【问题讨论】:

  • 你为什么不试试看会发生什么?试试看你为什么不看看会发生什么。
  • 首先你应该修复代码,使其成为有效的 Python

标签: python try-catch


【解决方案1】:

它使用引发的参数退出程序:

试用过的代码:

try:
    print(3+2)
finally:
    print('Goodby World!')
raise KeyboardInterrupt 
print(343)

输出:

5
Goodby World!
Traceback (most recent call last):
  File "lists.py", line 5, in <module>
    raise KeyboardInterrupt
KeyboardInterrupt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2013-08-13
    • 2020-06-05
    • 2016-02-12
    相关资源
    最近更新 更多