python common errors and exceptions! Incidental treatment method

Keywords: Python Programming REST

As a Python beginner, when learning Python programming, we often see some error messages.

Python has two types of errors that are easy to recognize: syntax errors and exceptions.

Python assert is used to judge an expression and trigger an exception when the expression condition is false.

syntax error

Python syntax errors, or parsing errors, are often encountered by beginners, as follows

>>> while True print('Hello world')
File "<stdin>", line 1, in ?

while True print('Hello world') ^ SyntaxError: invalid syntax

In this example, the function print() is detected to have an error, because it is preceded by a colon:.

The parser points out the line where the error occurred and marks a small arrow where the error was first found.


Even if the syntax of a Python program is correct, errors can occur when running it. Errors detected at run time are called exceptions.

Most of the exceptions will not be handled by the program, but will be displayed in the form of error messages


>>> 10 * (1/0)             # 0 cannot be used as a divisor, triggering an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3             # spam undefined, exception triggered
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2               # int cannot be added with str, triggering an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Exceptions occur in different types, all of which are printed as part of the message: the types in the example are ZeroDivisionError, NameError, and TypeError.

The front part of the error message shows the context in which the exception occurred and displays the specific information in the form of a call stack.

exception handling


Exception catching can use the 'try / exception' statement

In the following example, the user is asked to enter a legal integer, but the user is allowed to interrupt the program (using Control-C or the method provided by the operating system). A KeyboardInterrupt exception is thrown when the user interrupts.

while True:
        x = int(input("Please enter a number: "))
    except ValueError:
        print("You input is not a number, please try again!")

The try statement works as follows:;

  • First, execute the try clause (the statement between the keyword try and the keyword except).
  • After the end of the exception clause, if the exception clause is not executed.
  • If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the type of the exception matches the name after except, the corresponding exception clause is executed.
  • If an exception does not match any exceptions, the exception is passed to the upper try.

A try statement may contain multiple except clauses to handle different specific exceptions. At most one branch will be taken.

The handler will only handle exceptions in the corresponding try clause, not those in other try's handlers.

An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in brackets to form a tuple. For example:

except (RuntimeError, TypeError, NameError):


The last exception clause ignores the name of the exception, which is used as a wildcard. You can use this method to print an error message and throw the exception again.

import sys

    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
    print("Unexpected error:", sys.exc_info()[0])


The try/except statement also has an optional else clause, which, if used, must be placed after all except clauses.

The else clause is executed when no exception occurs in the try clause.

The following example judges whether the file can be opened in the try statement. If no exception occurs when opening the file, execute the else part of the statement to read the file content:

for arg in sys.argv[1:]:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
        print(arg, 'has', len(f.readlines()), 'lines')

It is better to use the else clause than to put all the statements in the try clause, so as to avoid some unexpected exceptions that can not be caught by exception.

Exception handling does not only deal with exceptions that happen directly in the try clause, but also handles exceptions thrown in functions that are called in the clause (or even indirectly called functions). For example:

>>> def this_fails():
        x = 1/0
>>> try:
    except ZeroDivisionError as err:
        print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero

Try finally statement

The try finally statement executes the last code whether an exception occurs or not.


In the following example, the finally statement is executed regardless of whether an exception occurs:


except AssertionError as error:
        with open('file.log') as file:
            read_data =
    except FileNotFoundError as fnf_error:
    print('This statement is executed regardless of whether the exception occurs or not.')

Throw an exception

Python throws a specified exception using the raise statement.

The syntax format of raise is as follows:

raise [Exception [, args [, traceback]]]

Click on the link: Learn more about python dry goods!

The following example triggers an exception if x is greater than 5:

x = 10
if x > 5:
    raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x))

Executing the above code will trigger an exception:

Traceback (most recent call last):
  File "", line 3, in <module>
    raise Exception('x Cannot be greater than 5. x The value of is: {}'.format(x))
Exception: x Cannot be greater than 5. x The value of is: 10

The only parameter to raise specifies the Exception to be thrown. It must be an instance of an Exception or a class of Exception (that is, a subclass of Exception).

If you just want to know if this throws an exception and don't want to handle it, a simple raise statement can throw it again.

>>> try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
An exception flew by!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
NameError: HiThere

User defined exception

You can have your own exceptions by creating a new exception class. Exception class inherits from exception class and can be inherited directly or indirectly. For example:

>>> class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
>>> try:
        raise MyError(2*2)
    except MyError as e:
        print('My exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

In this example, the class Exception defaults to__ init__ () is covered.

Classes with < p exceptions can do anything just like other classes, but they are usually relatively simple. They only provide some error related properties, and allow code handling exceptions to easily obtain these information. < p="">

When creating a module may throw many different exceptions, it is a common practice to create a base exception class for the package, and then create different subclasses for different error conditions based on the basic class

class Error(Exception):
    """Base class for exceptions in this module."""

class InputError(Error):
    """Exception raised for errors in the input.

        expression -- input expression in which the error occurred
        message -- explanation of the error

    def __init__(self, expression, message):
        self.expression = expression
        self.message = message

class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not

        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed

    def __init__(self, previous, next, message):
        self.previous = previous = next
        self.message = message

Most exceptions end with "Error", just like the standard exception names.

Define cleanup behavior

The try statement also has an optional clause that defines the cleanup behavior that will be performed in any case. For example:

>>> try:
...     raise KeyboardInterrupt
... finally:
...     print('Goodbye, world!')
Goodbye, world!
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>

In the above example, the finally clause will be executed regardless of whether there is an exception in the try clause.

If an exception is thrown in the try clause (or in the except and else clauses), and no exception intercepts it, the exception is thrown after the finally clause is executed.

Here is a more complex example (except and finally clauses in the same try statement)

>>> def divide(x, y):
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
            print("result is", result)
            print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined cleanup behavior

Some objects define a standard clean-up behavior. Whether or not the system successfully uses it, the standard cleanup behavior will be performed once it is no longer needed.

This example shows trying to open a file and print it to the screen

for line in open("myfile.txt"):
    print(line, end="")

The problem with the above code is that after execution, the file will remain open and not closed.

The keyword with statement can ensure that objects such as files will be cleaned up correctly after use

with open("myfile.txt") as f:
    for line in f:
        print(line, end="")

After the above code is executed, even if something goes wrong during the processing, the file f will always be closed.

Posted by michaelmuller on Mon, 29 Jun 2020 20:17:42 -0700