Что означает syntax error

Nick McCullum

Software Developer & Professional Explainer

SyntaxError in Python: How to Handle Invalid Syntax in Python

Syntax errors are the single most common error encountered in programming.

Regardless of the language used, programming experience, or the amount of coffee consumed, all programmers have encountered syntax errors many times.

Syntax problems manifest themselves in Python through the SyntaxError exception. In this tutorial, I will teach you how to handle SyntaxError in Python, including numerous strategies for handling invalid syntax in Python.

What is a SyntaxError ?

Syntax is the arrangement of words and phrases to create valid sentences in a programming language. A syntax error, in general, is any violation of the syntax rules for a given programming language.

With any human language, there are grammatical rules that we all must follow to convey meaning with our words. This is linguistic equivalent of syntax for spoken languages.

Programming languages attempt to simulate human languages in their ability to convey meaning. This means they must have syntax of their own to be functional and readable.

Syntax errors occur when a programmer breaks the grammatic and structural rules of the language. Syntax errors exist in all programming languages and differ based on the language’s rules and structure.

In compiled languages such as C or Java, it is during the compilation step where SyntaxErrors are caught and raised to the developer. This is a compiler error as opposed to a runtime error.

According to Python’s official documentation, a SyntaxError Exception is:

exception SyntaxError Raised when the parser encounters a syntax error. This may occur in an import statement, in a call to the built-in functions exec() or eval(), or when reading the initial script or standard input (also interactively).

This is a very general definition and does not help us much in avoiding or fixing a syntax error. It’s important to understand that these errors can occur anywhere in the Python code you write.

To be more specific, a SyntaxError can happen when the Python interpreter does not understand what the programmer has asked it to do.

Here is a simple example of a common syntax error encountered by python programmers.

This code will raise a SyntaxError because Python does not understand what the program is asking for within the brackets of the function. This is because the programming included the int keywords when they were not actually necessary. In Python, there is no need to define variable types since it is a dynamically typed language.

Because of this, the interpreter would raise the following error:

When a SyntaxError like this one is encountered, the program will end abruptly because it is not able to logically determine what the next execution should be. The programmer must make changes to the syntax of their code and rerun the program.

The Most Common SyntaxError in Python

The following code demonstrates what might well be the most common syntax error ever:

Can you find the error?

The missing punctuation error is likely the most common syntax mistake made by any developer.

The infamous «Missing Semicolon» in languages like C, Java, and C++ has become a meme-able mistake that all programmers can relate to. This is such a simple mistake to make and does not only apply to those elusive semicolons.

In the case of our last code block, we are missing a comma , on the first line of the dict definition which will raise the following:

After looking at this error message, you might notice that there is no problem with that line of the dict definition! You are absolutely right. The error is not with the second line of the definition, it is with the first line.

Error messages often refer to the line that follows the actual error. This causes some confusion with beginner Python developers and can be a huge pain for debugging if you aren’t already aware of this.

The reason this happens is that the Python interpreter is giving the code the benefit of the doubt for as long as possible.

When defining a dict there is no need to place a comma on the last item: ‘Robb’: 16 is perfectly valid.

So, when the interpreter is reading this code, line by line, ‘Bran’: 10 could very well be perfectly valid IF this is the final item being defined in the dict .

The interpreter gives you the benefit of the doubt for this line of code, but once another item is requested for this dict the interpreter suddenly realizes there is an issue with this syntax and raises the error.

Python is unique in that it uses indendation as a scoping mechanism for the code, which can also introduce syntax errors.

Because of this, indentation levels are extremely important in Python. To see this in action, consider the following code block:

Since this code block does not follow consistent indenting, it will raise a SyntaxError .

Normally indentation is 2 or 4 spaces (or a single tab — that is a hotly-debated topic and I am not going to get into that argument in this tutorial). This is very strictly controlled by the Python interpreter and is important to get used to if you’re going to be writing a lot of Python code.

Читайте также:  Serialization error action needed как исправить ошибку

Python3’s Print Function

Another extremely common syntax mistake made by python programming is the misuse of the print() function in Python3.

If you have recently switched over from Python v2 to Python3 you will know the pain of this error:

In Python version 2, you have the power to call the print function without using any parentheses to define what you want the print. Python3 removed this functionality in favor of the explicit function arguments list.

This error is so common and such a simple mistake, every time I encounter it I cringe!

Another very common syntax error among developers is the simple misspelling of a keyword.

Keywords are reserved words used by the interpreter to add logic to the code. For example: for , while , range , break , continue are each examples of keywords in Python.

Let’s take a look at an example of a mispelled keyword in Python:

This mistake is very common because it can be caused by a slip of the finger when coding quickly. Maybe you’ve had a bit too much coffee? Or not enough? In any case, these errors are often fairly easy to recognize, which makes then relatively benign in comparison to more complex bugs.

Misuse of Keywords

Similarly, you may encounter a SyntaxError when using a Python keyword incorrectly.

The break keyword can only serve one purpose in Python: terminating a loop. That being the case, there isn’t ever going to be used for the break keyword not inside a loop.

If you attempt to use break outside of a loop, you are trying to go against the use of this keyword and therefore directly going against the syntax of the language. This raises a SyntaxError .

Missing a Closing Symbol

Let’s consider an example:

This error is raised because of the missing closing quote at the end of the string literal definition.

As implied earlier, this same error is raised when dealing with parenthses:

This can be widely avoided when using an IDE which usually adds the closing quotes, parentheses, and brackets for you.

In summary, SyntaxError Exceptions are raised by the Python interpreter when it does not understand what operations you are asking it to perform.

The SyntaxError exception is most commonly caused by spelling errors, missing punctuation or structural problems in your code. These are the grammatical errors we find within all languages and often times are very easy to fix.

For the most part, these are simple mistakes made while writing the code. For the most part, they can be easily fixed by reviewing the feedback provided by the interpreter.


8. Errors and Exceptions¶

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

8.1. Syntax Errors¶

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the function print() , since a colon ( ‘:’ ) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

8.2. Exceptions¶

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal: you will soon learn how to handle them in Python programs. Most exceptions are not handled by programs, however, and result in error messages as shown here:

The last line of the error message indicates what happened. Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError , NameError and TypeError . The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception occurred, in the form of a stack traceback. In general it contains a stack traceback listing source lines; however, it will not display lines read from standard input.

Built-in Exceptions lists the built-in exceptions and their meanings.

8.3. Handling Exceptions¶

It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until a valid integer has been entered, but allows the user to interrupt the program (using Control — C or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.

Читайте также:  Unreal engine sdk error

The try statement works as follows.

First, the try clause (the statement(s) between the try and except keywords) is executed.

If no exception occurs, the except clause is skipped and execution of the try statement is finished.

If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block.

If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print B, C, D in that order:

Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except clause is triggered.

When an exception occurs, it may have associated values, also known as the exception’s arguments. The presence and types of the arguments depend on the exception type.

The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args .

The exception’s __str__() output is printed as the last part (‘detail’) of the message for unhandled exceptions.

BaseException is the common base class of all exceptions. One of its subclasses, Exception , is the base class of all the non-fatal exceptions. Exceptions which are not subclasses of Exception are not typically handled, because they are used to indicate that the program should terminate. They include SystemExit which is raised by sys.exit() and KeyboardInterrupt which is raised when a user wishes to interrupt the program.

Exception can be used as a wildcard that catches (almost) everything. However, it is good practice to be as specific as possible with the types of exceptions that we intend to handle, and to allow any unexpected exceptions to propagate on.

The most common pattern for handling Exception is to print or log the exception and then re-raise it (allowing a caller to handle the exception as well):

The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause. For example:

8.4. Raising Exceptions¶

The raise statement allows the programmer to force a specified exception to occur. For example:

The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from BaseException , such as Exception or one of its subclasses). If an exception class is passed, it will be implicitly instantiated by calling its constructor with no arguments:

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

8.5. Exception Chaining¶

If an unhandled exception occurs inside an except section, it will have the exception being handled attached to it and included in the error message:

To indicate that an exception is a direct consequence of another, the raise statement allows an optional from clause:

This can be useful when you are transforming exceptions. For example:

It also allows disabling automatic exception chaining using the from None idiom:

For more information about chaining mechanics, see Built-in Exceptions .

8.6. User-defined Exceptions¶

Programs may name their own exceptions by creating a new exception class (see Classes for more about Python classes). Exceptions should typically be derived from the Exception class, either directly or indirectly.

Читайте также:  Error это приложение не позволяет вам перезагрузить компьютер

Exception classes can be defined which do anything any other class can do, but are usually kept simple, often only offering a number of attributes that allow information about the error to be extracted by handlers for the exception.

Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may occur in functions they define.

8.7. Defining Clean-up Actions¶

The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:

If a finally clause is present, the finally clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception. The following points discuss more complex cases when an exception occurs:

If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.

An exception could occur during execution of an except or else clause. Again, the exception is re-raised after the finally clause has been executed.

If the finally clause executes a break , continue or return statement, exceptions are not re-raised.

If the try statement reaches a break , continue or return statement, the finally clause will execute just prior to the break , continue or return statement’s execution.

If a finally clause includes a return statement, the returned value will be the one from the finally clause’s return statement, not the value from the try clause’s return statement.

A more complicated example:

As you can see, the finally clause is executed in any event. The TypeError raised by dividing two strings is not handled by the except clause and therefore re-raised after the finally clause has been executed.

In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.

8.8. Predefined Clean-up Actions¶

Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed. Look at the following example, which tries to open a file and print its contents to the screen.

The problem with this code is that it leaves the file open for an indeterminate amount of time after this part of the code has finished executing. This is not an issue in simple scripts, but can be a problem for larger applications. The with statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines. Objects which, like files, provide predefined clean-up actions will indicate this in their documentation.

8.9. Raising and Handling Multiple Unrelated Exceptions¶

There are situations where it is necessary to report several exceptions that have occurred. This is often the case in concurrency frameworks, when several tasks may have failed in parallel, but there are also other use cases where it is desirable to continue execution and collect multiple errors rather than raise the first exception.

The builtin ExceptionGroup wraps a list of exception instances so that they can be raised together. It is an exception itself, so it can be caught like any other exception.

By using except* instead of except , we can selectively handle only the exceptions in the group that match a certain type. In the following example, which shows a nested exception group, each except* clause extracts from the group exceptions of a certain type while letting all other exceptions propagate to other clauses and eventually to be reraised.

Note that the exceptions nested in an exception group must be instances, not types. This is because in practice the exceptions would typically be ones that have already been raised and caught by the program, along the following pattern:

8.10. Enriching Exceptions with Notes¶

When an exception is created in order to be raised, it is usually initialized with information that describes the error that has occurred. There are cases where it is useful to add information after the exception was caught. For this purpose, exceptions have a method add_note(note) that accepts a string and adds it to the exception’s notes list. The standard traceback rendering includes all notes, in the order they were added, after the exception.

For example, when collecting exceptions into an exception group, we may want to add context information for the individual errors. In the following each exception in the group has a note indicating when this error has occurred.


Оцените статью