e-holder
e-holder

Reputation: 1564

Why does struct.pack throw an exception that seems to have no type?

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

Answers (1)

payloc91
payloc91

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

Related Questions