Python Programming by Example (2015)

9. Error Handling

This chapter explains how to handle errors and exceptions that occur in Python application.

9.1 Error Handling

Basically when we write a program and occur error on running, Python will catch program error. 

Try to write these scripts and run this program.

a = 18

b = 0

c = a / b

$ python3 ch09_01.py

You should get error, shown in Figure below.

p9-1

Now we can catch error using try..except. You can read how to use it on https://docs.python.org/3/tutorial/errors.html .

Write these scripts.

try:

    a = 18

    b = 0

    c = a / b

    print('result:', str(c))

except ZeroDivisionError as e:

    print('Error: division by zero')

    print(e)

finally:

    print('Done')

print('exit from program')

Save into a file, ch09_02.py. Then, run the file.

$ python3 ch09_02.py

You can see the program can handle the error.

p9-2

9.2 Catching All Errors

On previous section, we catch error for "division by error". We can catch all errors using Exception object. Write these scripts for demo.

try:

    a = 18

    b = 0

    c = a / b

    print('result:', str(c))

except Exception as e:

    print(e)

finally:

    print('Done')

print('exit from program')

Save into a file, called ch09_03.py. Run the program.

$ python3 ch09_03.py

Program output:

p9-3

9.3 Raising Exceptions

We can raise error from our program using raise.

For demo, write these scripts.

try:

    a = 18

    b = 0

    c = a / b

    print('result:', str(c))

except Exception as e:

    raise

finally:

    print('Done')

# this code is never called

print('exit from program')

Save into a file, called ch09_04.py. Then, run the program.

$ python3 ch09_04.py

You should the program raise the error so we don't words "exit from program".

p9-4

9.4 Custom Exception

We can build own error with implementing inheritance Exception.

For instance, we create a class, MySimpleError, with inheritance from Exception.

class MySimpleError(Exception):

    def __init__(self, code, message):

        self.code = code

        self.message = message

    def __str__(self):

        return repr(str(self.code) + ":" + self.message)

    def save_to_database(self):

        print('save this error into database..')

# how to use custom error

try:

    print('demo custom error')

    print('raise error now')

    raise MySimpleError(100,'This is custom error')

except MySimpleError as e:

    print(e)

    e.save_to_database()

Save the program into a file, called ch09_05.py. 

Run this program.

$ python3 ch09_05.py

Program output:

p9-5