Exception capture and print

I’m working through intermediate Python 3 specifically the Catching Specific Exceptions module:
https://www.codecademy.com/courses/learn-intermediate-python-3/lessons/int-python-exceptions/exercises/catching-specific-exceptions

Im wondering if there is a blanket statement that will save the specific exception encountered and print it?
currently I have:

for location, staff in staff.items():
try:
print_staff_report(location, staff)
except Exception as e:
print('Could not print sales report for ’ + location)
print(str(e))
print()

While this seems to do mostly what I want, I was hoping I could get the actual error encountered to print. For example, if I change the key ‘floor managers’ under Melbourne It just prints ‘floor manager’ instead of KeyError or the specific type of error it encountered. Im pretty sure I should know how to do this but I can’t seem to recall exactly how!
I understand what I’m doing just curious if that is possible rather than listing a tuple with every possible exception it might encounter1

Thanks!

I believe what you’re looking for is the type() function in python. Errors also have a type, and that type is actually the exception type that it is. So a ValueError has a class of ValueError for example. Therefore if you want to print this out, you need to get the __name__ built-in attribute from the type function, like so:

type(e).__name__

Unfortunately I don’t have access to the lesson, but see the example codepen below for how it would print.

staff = {"one": "one", "two": "two", "three": "NaN"} for location, staff in staff.items(): try: print(location, int(staff)) except Exception as e: print('Could not print sales report for ' + location) print(type(e).__name__ + ": " + str(e)) print()

ok super! I was trying to use the type but getting syntax errors. I was definitely doing that wrong thanks for the pointer!

1 Like