本文介绍了可以处理语法错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

try:
    if True a = 1  #It's missing a colon So it's a SyntaxError!!!!!!!
except SyntaxError:
    print 'hey'

您期望它打印但是它会引发 SyntaxError ,这是我想避免的错误。那么可以使用 try-except 块来处理所有异常吗?好吧,如果 SyntaxError 是一个例外,为什么将它包含在?最后如何解决上面的代码,以便它可以正确处理异常?

You'd expect it to print hey However It raises a SyntaxError, The same error I'm trying to avoid. So Can all Exceptions be handled using a try-except block? Well If SyntaxError's were an exception why is it included in the built-in exceptions? and finally how can I fix the above piece of code so that it handles the exception properly?

注意:我知道我要做什么完全是没有意义,没有实际目的

推荐答案

SyntaxError 是一个完全普通的内置异常。它在任何方面都不是特别的。

SyntaxError is a perfectly ordinary built-in exception. It is not special in any way. Only the circumstances of when it's (usually) thrown are a bit unusual.

语法错误意味着无法解析带有该错误的代码 。它甚至还不是一个有效的程序,因此无法执行。因此,在程序运行之前,在 之前引发了 SyntaxError 异常,因此无法从程序中捕获该异常。

A syntax error means that the code featuring said error cannot be parsed. It doesn't even begin to be a valid program, hence it cannot be executed. Therefore SyntaxError exceptions are raised before the program is run, and hence can't be caught from within the program.

更具体地说,此异常是由解析器引发的。因为解析器在代码执行之前就完全运行,而不是与之交错,所以程序无法捕获其自身的语法错误。

More specifically, this exception is raised by the parser. Because the parser runs fully before the code is executed, rather then interleaved with it, a program can't catch its own syntax errors.

解析器本身就是另一个程序但是:调用解析器的代码可以像其他所有异常一样捕获 SyntaxError (因为 is 与其他所有异常一样)。 调用解析器的示例包括:

The parser itself is just another program though: Code invoking the parser can catch SyntaxErrors like every other exception (because it is like every other exception). Examples of "invoking the parser" include:


  • compile exec eval

  • import 语句

  • 模块中的多个功能,例如 ast tokenizer 解析器,等等。

  • compile, exec, eval
  • import statements
  • Several functions in modules like ast, tokenizer, parser, etc.

这篇关于可以处理语法错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:01