Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating our own exceptions


The hierarchy of exceptions has a superclass for error-related exceptions, called Exception. All of the exceptions which reflect essentially erroneous conditions are subclasses of the Exception class. The base class for all exceptions is the BaseException class; some non-error-related exceptions are direct subclasses of the BaseException class.

We can summarize the hierarchy like this:

  • BaseException

    • SystemExit

    • KeyboardInterrupt

    • GeneratorExit

    • Exception

      • All other exceptions

The superclass of all error-related exceptions, Exception, is quite broad. We can use this in a long-running server like this:

def server():
        try:
        while True:
            try:
                one_request()
            except Exception as e:
                print(e.__class__.__name__, e)
    except Shutdown_Request:
        print("Shutting Down")

This example depends on a function, one_request(), which handles a single request. The while loop runs forever, evaluating the one_request...