Exceptions

Raise

Try..except

Assert

Plutôt qu’utiliser raise, on peut également utiliser l’instruction assert pour lancer une exception AssertionError si une condition donnée est fausse.

try:
    assert 1 == 2
except AssertionError as e:
    print('Err:', e)

# Err: 
try:
    assert 1 == 2, "1 est différent de 2"
except AssertionError as e:
    print('Err:', e)

# Err: 1 est différent de 2

Classes

Les exceptions natives de Python sont les suivantes:

BaseException
    SystemExit
    KeyboardInterrupt
    GeneratorExit
    Exception
        StopIteration
        ArithmeticError
            FloatingPointError
            OverflowError
            ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EnvironmentError
            IOError
            OSError
        EOFError
        ImportError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        ReferenceError
        RuntimeError
            NotImplementedError
        SyntaxError
            IndentationError
            TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            DeprecationWarning
            PendingDeprecationWarning
            RuntimeWarning
            SyntaxWarning
            UserWarning
            FutureWarning
            ImportWarning
            UnicodeWarning
            BytesWarning

Built-in Exceptions in Python