语法错误和运行时错误有什么区别? [英] What is the difference between syntax error and runtime error?

查看:705
本文介绍了语法错误和运行时错误有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

def tofloat(i): 
    return flt(i)

def addnums(numlist):
    total = 0
    for i in numlist:
        total += tofloat(i)
    return total

nums = [1 ,2 ,3]
addnums(nums)

flt 应该是 float ,但是我很困惑,无论是语法错误还是运行时错误。

The flt is supposed to be float, but I'm confused whether it is a syntax error or a runtime error.

推荐答案

其实这是一个运行时错误,因为Python会尝试解决 flt 在运行时(因为它是一种动态语言),它不会找到它。当这种情况发生时,Python产生和异常,说它找不到你使用的符号 flt ,所有这些都发生在运行时。

Actually, it is a runtime error, because Python will try to resolve the flt name during runtime (because it's a dynamic language), and it won't find it. When this happens, Python yields and exception saying that it couldn't find the symbol you were using flt and all this happens at runtime.

当解释器找到不符合Python语法的东西时,会发生语法错误。例如:Python的语法不能将输入语法识别为有效的Python程序。这可能会发生在以下情况:

Syntax errors happen when the interpreter find something not compelling with Python's syntax. For example: The Python's grammar doesn't recognize the input syntax as a valid Python program. This may happen when:


  1. 您忘记添加 if,def,class 等表达式

  2. 您忘了关闭一些括号或括号等。

  3. 当你不遵守python的语法时,还有很多地方:)

  1. You forgot to add : at the end of an if, def, class, etc expression
  2. You forgot to close some parenthesis or brackets, etc.
  3. A lot of places else when you don't adhere to python's grammar :)

在你的例子中,没有什么错误的语法对于解释器, flt(i)是对 flt 方法的非常有效的调用,必须在运行时检查在范围内,如果它真的存在。所以解释者不会投诉,你的问题的语法很好。

In your example, there is nothing wrong with the grammar. For the interpreter, flt(i) is a very valid call to a flt method which had to be check at runtime within the scopes if it really exists. So the interpreter won't complaint and the syntax of your problem is good.

实际上,这可以被看作是编译语言的缺点像C#,C ++等。这样的错误可以在编译时被更早地检测到,编译器在找到它时会大声尖叫,以便您可以注意到。

Actually, this can be seen as a disadvantage over compiled languages like C#, C++, etc. This kind of errors can be detected sooner at compile time, and the compiler screams loud when it find it so you can notice it.

动态语言,您将不会注意到,直到实际的方法被调用。你的程序很简单,所以你可以快速找到它。但是, float 中缺少的 o 在类的一个子类的一个子类中的一些遗留框架内,作为一个财产,在一些其他模块内部等等。这将是苛刻的:)

With dynamic languages, you won't notice this until the actual method is called. Your program is simple, so you may find it quick. But, what about the missing o in float was inside some legacy framework within a subclass of a subclass of a class, as a property, inside some other module, etc. That would be harsh :)

更新: Python的文档中的执行模型是一个很好的阅读,如果你涉及到Python内部的工作原理。这将进一步澄清您的疑问,并将为您提供很多知识:)

UPDATE: The execution model in Python's docs are a great read if you're into how does Python internals works. This will clarify your doubt further and will give you a lot of knowledge :)

希望这有帮助!

这篇关于语法错误和运行时错误有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆