Reputation: 1564
I want to use the correct exception type instead of the generic except Exception
, however, I'm not sure how to find the proper type. Here is a code snippet to demonstrate the behavior. Passing in a None
instead of an integer is not allowed as it's trying to pack it into an unsigned long.
>>> import struct
>>> try:
... b = struct.pack("L", None)
... except Exception as ex:
... print(f"An exception of type {type(ex).__name__} occurred. {ex.args}")
...
An exception of type error occurred. ('required argument is not an integer',)
What is the recommended way to catch an exception from pack? Or am I stuck with checking all the arguments to pack()
to make sure they are valid?
Upvotes: 2
Views: 913
Reputation: 3809
You are catching an exception of type struct.error
apparently.
As mentioned in the docs:
exception struct.error
Exception raised on various occasions; argument is a string describing what is wrong.
If you just do
print(f"{type(ex)}")
it prints <class 'struct.error'>
Also, just to confirm
try:
struct.pack("L", None)
except struct.error as ex:
print("Caught")
prints Caught
Upvotes: 2