Working with exceptions in python


BaseException
  SystemExit (on sys.exit)
  Exception
    RuntimeError
    other various errors

message = "some error"
someObj1 = None
someObj2 = None


# Most of the time
# The first argument is a string (always)
raise Exception(message)

# you can do this with additional objects
raise Exception(message, someObj1, someObj2)

Language reference for exceptions

Built in class library for exception

  1. It is not clear from the docs what the inputs are for these class constructors
  2. The base class args are not particularly redefined in the derived class making it very confusing :)

try:
    # Code that might raise an exception
    # ...
except ExceptionType1:
    # Handle ExceptionType1
    # ...
except ExceptionType2:
    # Handle ExceptionType2
    # ...
# Add more except blocks as needed
else:
    # Optional: Code to run if no exception was raised in the try block
finally:
    # Optional: Code that always runs, whether an exception was raised or not

try:
    result = 10 / 0  # Attempt to divide by zero
except ZeroDivisionError:
    print("Error: Division by zero")
else:
    print(f"Result: {result}")
finally:
    print("Execution completed, regardless of exceptions")

try:
    custom_data = {"key": "value"}
    raise Exception("This is a simple exception", custom_data)
except Exception as e:
    print(f"Exception: {e}")  # Access the exception object
    print(f"Custom Data: {e.args[1]}")  # Access the custom data
    import traceback
    traceback.print_exc()  # Print the traceback information

try:
 ...
except SomeException s:
   raise "Something else happened" from s

import traceback
traceback.print_exc()

Traceback is documented here: traceback module in standard libray

There are lot of good examples of using traceback at the link above.