Exceptions

Built-in Exceptions

In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

Exception hierarchy

BaseException
    +-- SystemExit
    +-- KeyboardInterrupt
    +-- GeneratorExit
    +-- Exception
        +-- <ANY-OTHER-EXCEPTION>

Example

def process(the_list):
    try:
        assert(len(the_list)>0)
        if the_list[1] in the_list:
            raise ValueError("Value Error!!!")
    except IndexError as e:
        print(e)
        raise Exception("Exception: ", e)
    except ValueError as e:
        print(e)
        raise Exception("Exception: ", e)
    except Exception as e:
        print(e)
        raise Exception("Exception: ", e)
    else:
        print("No exceptions found")
    finally:
        print("Exception handling done")
    print("processing done")

n_list = []
for n in range(0, 3):
    print(n, n_list)
    try:
        process(n_list)
    except Exception as e:
        print("Exception while processing: ", e)
    finally:
        n_list.append(n)
    print()

Output:

0 []

Exception handling done
Exception while processing:  ('Exception: ', AssertionError())

1 [0]
list index out of range
Exception handling done
Exception while processing:  ('Exception: ', IndexError('list index out of range'))

2 [0, 1]
Value Error!!!
Exception handling done
Exception while processing:  ('Exception: ', ValueError('Value Error!!!'))