Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Errors and Exceptions

Python3 Errors and Exceptions

As a Python beginner, you often see error messages when first learning Python programming; we did not mention them earlier, and this chapter covers them specifically.

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

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

Syntax errors

Python syntax errors, also called parsing errors, are frequently encountered by beginners, as in the following example

while

True

print

(

'Hello world'

)

  File

""

,

line

1

,

in

?

   

while

True

print

(

'Hello world'

)

                   ^

SyntaxError

: invalid syntax

In this example, the function print() is found to have an error: a colon : is missing before it.

The parser points out the line with the error and marks the position of the first error found with a small arrow.

exception

Even when a Python program's syntax is correct, errors can still occur while running it. Errors detected at runtime are called exceptions.

Most exceptions are not handled by the program and are displayed here as error messages:

Example

10

(

1

/

0

)

           

0 cannot be a divisor, triggering an exception

Traceback

(

most recent call last

)

:

  File

""

,

line

1

,

in

?

ZeroDivisionError

: division by zero

4

3

           

spam is undefined, triggering an exception

Traceback

(

most recent call last

)

:

  File

""

,

line

1

,

in

?

NameError

: name

'spam'

is

not

defined

'2'

2

             

int cannot be added to str, triggering an exception

Traceback

(

most recent call last

)

:

  File

""

,

line

1

,

in

<

module

TypeError

: can only concatenate

str

(

not

"int"

)

to

str

Exceptions appear in different types, and these types are printed as part of the message: the types in the examples are ZeroDivisionError, NameError, and TypeError.

The first part of the error message shows the context in which the exception occurred, with detailed information in the form of a call stack.

Exception handling

try/except

Exceptions can be caught with the try/except statement.

In the following example, the user is asked to enter a valid integer but is allowed to interrupt the program (using Control-C or a method provided by the operating system). The user's interrupt raises a KeyboardInterrupt exception.

while

True

:

   

try

:

        x

=

int

(

input

(

"Please enter a number: "

)

)

       

break

   

except

ValueError

:

       

print

(

"What you entered is not a number, please try again!"

)

The try statement works as follows;

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

A handler only handles exceptions in its corresponding try clause, not exceptions in the handlers of other try statements.

One except clause can handle several exceptions at once; these are put in parentheses as a tuple, for example:

except

(

RuntimeError

,

TypeError

,

NameError

)

:

   

pass

The last except clause may omit the exception name and acts as a wildcard. You can use this to print an error message and then re-raise the exception.

import

sys

try

:

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

)

except

:

   

print

(

"Unexpected error:"

,

sys

.

exc_info

(

)

[

0

]

)

   

raise

try/except...else

The try/except statement also has an optional else clause; if used, it must come after all except clauses.

The else clause executes when no exception occurs in the try clause.

The following example checks in a try statement whether a file can be opened; if opening the file succeeds without an exception, the else part reads the file contents:

for

arg

in

sys

.

argv

[

1

:

]

:

   

try

:

        f

=

open

(

arg

,

'r'

)

   

except

IOError

:

       

print

(

'cannot open'

,

arg

)

   

else

:

       

print

(

arg

,

'has'

,

len

(

f.

readlines

(

)

)

,

'lines'

)

        f.

close

(

)

Using an else clause is better than putting all statements inside the try clause, because it avoids unexpected exceptions that except cannot catch.

Exception handling covers not only exceptions occurring directly in the try clause, but also exceptions thrown in functions called by the clause (or even indirectly called functions). For example:

def

this_fails

(

)

:

        x

=

1

/

0

   

try

:

        this_fails

(

)

   

except

ZeroDivisionError

as

err:

       

print

(

'Handling run-time error:'

,

err

)

   

Handling run-

time

error:

int

division

or

modulo by zero

The try-finally statement

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

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

Example

try

:

    runoob

(

)

except

AssertionError

as

error:

   

print

(

error

)

else

:

   

try

:

       

with

open

(

'file.log'

)

as

file

:

            read_data

=

file

.

read

(

)

   

except

FileNotFoundError

as

fnf_error:

       

print

(

fnf_error

)

finally

:

   

print

(

'This line executes whether or not an exception occurs.'

)


Throwing an Exception

Python uses the raise statement to throw a specified exception.

The raise syntax is as follows:

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

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

x

=

10

if

x

5

:

   

raise

Exception

(

'x cannot be greater than 5. The value of x is: {}'

.

format

(

x

)

)

Running the code above raises an exception:

Traceback (most recent call last):
  File "test.py", line 3, in 
    raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
Exception: x 不能大于 5。x 的值为: 10

The single argument of raise specifies the exception to be thrown. It must be an exception instance or an exception class (i.e. a subclass of Exception).

If you only want to know whether an exception was raised and do not want to handle it, a simple raise statement can re-raise it.

try

:

       

raise

NameError

(

'HiThere'

)

 

Simulate an exception.

   

except

NameError

:

       

print

(

'An exception flew by!'

)

       

raise

   

An exception flew by

!

Traceback

(

most recent call last

)

:

  File

""

,

line

2

,

in

?

NameError

: HiThere


User-defined exceptions

You can have your own exceptions by creating a new exception class. Exception classes inherit from the Exception class, 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

""

,

line

1

,

in

?

main

.

MyError

:

'oops!'

In this example, the default init() of class Exception is overridden.

When creating a module that may raise several different exceptions, a common practice is to establish a base exception class for the package and then create different subclasses for different error conditions based on it:

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

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

    Attributes:
        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
    allowed.

    Attributes:
        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
        self.next = next
        self.message = message

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


Defining clean-up actions

The try statement has another optional clause that defines clean-up actions to be executed under all circumstances. For example:

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

In the example above, the finally clause executes whether or not an exception occurred in the try clause.

If an exception is raised in the try clause (or in an except or else clause) and no except catches it, the exception is re-raised after the finally clause executes.

Below is a more complex example (containing both except and finally clauses in the same try statement):

>>> def divide(x, y):
        try:
            result = x / y
        except ZeroDivisionError:
            print("division by zero!")
        else:
            print("result is", result)
        finally:
            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 "", line 1, in ?
  File "", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined clean-up actions

Some objects define standard clean-up actions that run once the object is no longer needed, whether or not the system used it successfully.

The following example shows opening a file and printing its contents to the screen:

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

The problem with the code above is that when it finishes, the file remains open and is not closed.

The with keyword guarantees that objects such as files always execute their clean-up methods properly after use:

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

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

For more on the with keyword, see:Python with keyword


Related content

Python assert

Python with keyword