Working with exceptions in python

satya - 1/19/2024, 4:10:37 PM

Exception hierarchy


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

satya - 1/19/2024, 4:18:04 PM

How do I raise an exception


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)

satya - 1/19/2024, 4:20:13 PM

Language reference for exceptions

Language reference for exceptions

satya - 1/19/2024, 4:28:48 PM

Built in class library for exception

Built in class library for exception

satya - 1/19/2024, 4:29:42 PM

However

  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 :)

satya - 1/19/2024, 4:33:15 PM

try syntax


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

satya - 1/19/2024, 4:33:31 PM

Example


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")

satya - 1/19/2024, 4:34:08 PM

Using trace back


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

satya - 1/19/2024, 4:38:55 PM

This is the most useful: raise...from..original


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

satya - 1/19/2024, 4:39:51 PM

Remember traceback.print_exc()


import traceback
traceback.print_exc()

satya - 1/19/2024, 4:42:50 PM

Traceback is documented here: traceback module in standard libray

Traceback is documented here: traceback module in standard libray

satya - 1/19/2024, 4:43:54 PM

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

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