可以正确处理语法错误吗

可以正确处理语法错误吗

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

问题描述

考虑以下代码:

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

你会期望它打印 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.

语法错误意味着不能解析具有错误的代码 。它甚至没有开始是一个有效的程序,因此它不能被执行。因此,程序运行之前,语法错误异常被引发,因此无法从程序中捕获。

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 ,因为它像其他异常一样 。 调用解析器的示例包括:

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:


  • 编译 exec eval

  • import 语句

  • 模块中的几个函数,如 ast tokenizer parser 等。

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

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

08-03 19:57