Resources

The RuntimeError exception is a catch-all which you can use for your own raising and subclassing errors.

Raise

>>> raise RuntimeError("Message")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Message

Catch and re-raise

Python 3 syntax - you donโ€™t have to catch and raise e explicitly.

try:
    foo = "My foo"
    bar(foo)
except Exception:
    print(f"Foo: {foo}")
    raise

Custom error

Basic

You can use pass or docstring or both.

class Foo(RuntimeError):
    """Description of Foo error"""
raise Foo("Message")

Output:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.Foo: Message
try:
    # Function call that raises this...
    raise NetworkError("Message")
except NetworkError as e:
    print(e)
    print(e.args)
Message
('Message',)

Override init

class NetworkError(RuntimeError):
    def __init__(self, msg):
        self.msg = msg

try:
    # Function call that raises this...
    raise NetworkError("Message")
except NetworkError as e:
    print(e.msg)

Output:

Message