向uuid.UUID()传入无效参数会发生什么?
myStatus = True
myUUID = uuid.UUID( someWeirdValue )
if myUUID == None:
myStatus = False
会出现异常吗?UUID()会不会在不发出任何警告的情况下失败?有没有可能在某种情况下,'myStatus'的值会变成False?
2 个回答
10
UUID()
这个构造函数会根据你传入的内容,可能会引发两种错误:TypeError
或ValueError
。
如果你没有传入任何hex
、bytes
、bytes_le
、fields
或int
这些选项,就会引发TypeError
;如果你传入了一个无效的值,就会引发ValueError
:
>>> uuid.UUID()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 129, in __init__
raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
TypeError: need one of hex, bytes, bytes_le, fields, or int
>>> uuid.UUID('abcd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 134, in __init__
raise ValueError('badly formed hexadecimal UUID string')
ValueError: badly formed hexadecimal UUID string
>>> uuid.UUID(bytes='abcd')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/uuid.py", line 144, in __init__
raise ValueError('bytes is not a 16-char string')
ValueError: bytes is not a 16-char string
等等。
它不会悄悄地失败。它绝对不会返回None
。要么myUUID
会被设置为一个UUID
实例,要么就会引发一个异常。