Syntax error


A syntax error is a mismatch in the syntax of data input to a computer system that requires a specific syntax. For source code in a programming language, a compiler detects syntax errors before the software is run, whereas an interpreter detects syntax errors at run-time. A syntax error can occur based on syntax rules other than those defined by a programming language. For example, typing an invalid equation into a calculator is a syntax error.
Some errors that occur during the translation of source code may be considered syntax errors by some but not by others. For example, some say that an uninitialized variable in Java is a syntax error, but others disagree classifying it as a static semantic error.

Examples

In Java

The Java compiler generates a syntax error for the following code since the string is not quoted. The compilation process fails and does not produce a usable executable.

System.out.println;

Valid syntax is:

System.out.println;

In Lisp

The code is a syntactically valid Lisp program that adds 1 and 1.
However, results in syntax error. The lexer is unable to identify the first error – all it knows is that, after producing the token LEFT_PAREN, ', and thus gives an error message; in general, it may be ambiguous grammar.
Type errors and undeclared variable errors are sometimes considered to be syntax errors when they are detected at compile-time, though it is common to classify these kinds of error as semantic errors instead.

In Python

For Python code, contains a type error because it adds a string literal to an integer literal. A type error like this can be detected at compile-time during parsing if the compiler uses separate rules that allow "integer-literal + integer-literal" but not "string-literal + integer-literal", though it is more likely that the compiler will use a parsing rule that allows expressions of the form "literal-or-identifier + literal-or-identifier" and then the error will be detected during contextual analysis. In some cases, this validation is not done by the compiler, and these errors are only detected at runtime.
In a dynamically typed language, where type can only be determined at runtime, many type errors can only be detected at runtime. For example, for Python is syntactically valid at the phrase level, but the correctness of the types of a and b can only be determined at runtime, as variables do not have types in Python, only values do. Whereas there is disagreement about whether a type error detected by the compiler should be called a syntax error, type errors which can only be detected at program execution time are always regarded as semantic rather than syntax errors.

On a calculator

A syntax error can occur on a calculator when the input equation is incorrect in ways such as: