Search code examples
pythonruntime-errorsyntax-error

Differentiating semantic error, logic error and runtime error


Today, I came across this exam question (This is not totally the same as the exam question but the idea is the same):

Which of the following codes is semantic error?

A) a = 'abc' + 123

B) for i in range(5)

C) b = 7/0

D) [i for i in range(10**19)]

As I've been taught during the lecture, generally, there are 4 types of errors: Syntax error, Runtime error, Logic error and Semantic error. On this basis, I figure that C, which returns ZeroDivisionError, is runtime error, logic error and semantic error. However, A, in my opinion, is also semantic error because maybe the programmer wanted to do a = 'abc' + '123'.

I know this topic has been brought up a lot, but I'm still so confused and can't spot the difference between these types of errors. If possible, could you give me an answer to the above question and also differentiate these definitions? Thank you in advance!


Solution

  • A semantic error is when a programmer misunderstands how the programming language works and writes code that doesn’t make sense in the context of the language’s rules. The code may be syntactically correct, but it violates the rules or “semantics” of the language. Therefore, the first piece of code is semantic error.

    The second piece of code is SyntaxError, the third is RuntimeError, and the last piece of code is either MemoryError or TimeoutError.