【问题标题】:try except not catching the exception [duplicate]尝试除了不捕获异常[重复]
【发布时间】:2018-08-27 19:51:55
【问题描述】:

我被告知空的except 会捕获各种异常,但是当我尝试这段代码时,它不会捕获异常并引发SyntaxError。我做错了什么?

try:
    print "Hello"
except:
    print("Caught!")  #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?

即使我将异常类型指定为SyntaxError它仍然无法捕获它。

try:
    print "Hello"
except SyntaxError:
    print("Caught!") #output: SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?

【问题讨论】:

标签: python python-3.x try-catch


【解决方案1】:

没有。一个空的 except 捕获所有类型的 runtime 错误;根据定义,语法错误不是运行时错误,因为代码根本无法运行。

【讨论】:

  • 你先搞定了! @Ayxan 代码无法编译。
  • –1 运行时可能出现语法错误。它们也可以在运行时被捕获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2021-12-13
  • 2011-12-05
  • 2014-05-11
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多