Latest web development tutorials

Python3 errors and exceptions

As a Python beginner, just learning the Python programming often see some error message, we did not mention in front of this chapter we will be devoted.

Python has two easily recognizable error: syntax errors and exceptions.

Grammatical errors

Python syntax errors or wrong call analytic, beginners often encounter, as examples

>>> 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 checked for errors before it is missing a colon (:).

Parser pointed out the error of his party, and in the wrong place to find the first marker a small arrow.


Even grammar Python program is correct, it's time to run, there may be errors. Runtime errors detected are called exceptions.

Most will not be an exception handler in the form of error messages display here:

>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: Can't convert 'int' object to str implicitly

Appear abnormal in different types, these types are printed out as part of the information: Examples of types ZeroDivisionError, NameError and TypeError.

The front part of the error message shows the context of an exception occurs, the call stack and displayed in the form of specific information.

Exception Handling

The following example, allows users to enter a valid integer, but allows the user to interrupt the program (using Control-C or the operating system methods provided). User interruptions will cause a KeyboardInterrupt exception.

>>> while True:
            x = int(input("Please enter a number: "))
        except ValueError:
            print("Oops!  That was no valid number.  Try again   ")

try statement works as follows;

  • First, the try clause (between the keywords and keyword except try statements)
  • If no exception occurs, the except clause is ignored, try clause is executed ends.
  • If an exception occurs in the try clause procedure, then try clause, the rest will be ignored. If the name and type of the exception except after the match, then the corresponding except clause is executed. Code try statement after the last execution.
  • If an exception does not match with any except, this exception will be passed to the upper try.

A try statement may contain more than one except clause, to deal with different specific exceptions. At most one branch will be executed.

Handler only for the corresponding try clause exception processing, rather than the other try exception handler.

An except clause can handle multiple exceptions that will be placed in a parenthesis as a tuple, for example:

    except (RuntimeError, TypeError, NameError):

The last except clause may ignore the name of the exception, it will be treated as a wildcard. You can use this method to print an error message, and then again thrown.

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])

try except statement has an optional else clause, if you use this clause, must be placed after all except clauses. This clause will not have any problem occurs in the try clause executes. E.g:

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

Use the else clause than all the statements in the try clause which is better to avoid some unexpected, but except they did not catch the exception.

Exception handling not only deal with those exceptions occur directly try clause, but also to call handler clause (even indirect function calls) where thrown. E.g:

>>> 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

Throw an exception

Python uses throw statement to raise a specified exception. E.g:

>>> raise NameError('HiThere')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: HiThere

raise only one parameter specifies the exception to be thrown. It must be an unusual instance of a class or abnormal (ie Exception subclass).

If you want to know if it throws an exception, does not want to deal with it, then a simple statement can raise it again thrown.

>>> 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 exceptions

You can have your own exceptions by creating a new exception class. Exceptions should inherit from the Exception class, either directly inheritance, succession 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 default __init __ () is overwritten.

When creating a module may throw a variety of abnormal A common practice is to create a base exception class for this package, and then based on this base class to create different sub-classes for different error conditions:

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 of the names are the exception to the "Error" at the end, just like a standard naming as abnormal.

Defined cleanup behavior

try statement has another optional clause, which defines the clean-up behavior under any circumstances will perform. E.g:

>>> try:
        raise KeyboardInterrupt
        print('Goodbye, world!')
Goodbye, world!

Regardless of the above examples try clause, there is no exception occurs, finally clause is executed.

If an exception in the try clause (or except and else clause) was thrown out, but do not have any except it stopped, then this will be raised again after the finally clause is executed.

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

>>> 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 standard clean-up behavior, regardless of whether the system is successfully used it once do not need it, then clean up this standard behavior is executed.

This example shows this side try to open a file and then print the contents on the screen:

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

The above problem with this code is that when finished, the file remains open, not closed.

Keywords with statement can be guaranteed objects such as files will be finished using the correct execution of his clean-up methods:

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

After the above code is finished, even if the problems in the process, the file f is always closed.