我是Python新手,我試圖處理錯誤,但我不知道最有效的方式來處理Python中的錯誤。我以這種方式嘗試過,但看起來有點複雜。我認爲可能存在一些其他「更好」的方式來處理它。什麼是最有效的方式來處理Python中的錯誤?
def set_bit(value, pos, nbits):
"""
Set bit at position.
Keyword Arguments
value (int)
Bitstring value.
pos (int)
Position to set bit.
nbits (int)
Number of bits.
"""
if isinstance(value, int):
if value > -1:
# Positives only
if isinstance(pos, int):
if pos > -1:
if isinstance(nbits, int):
if nbits > -1:
return get_bistring(value | 2 ** (pos % nbits), nbits)
else:
raise ValueError(
'"nbits" was set {}, but it must be positive only'
.format(nbits)
)
else:
raise TypeError(
'"nbits" was set {}, but it must be int only'
.format(type(nbits))
)
else:
raise ValueError(
'"pos" was set {}, but it must be positive only'
.format(pos)
)
else:
raise TypeError(
'"pos" was set {}, but it must be int only'
.format(type(pos))
)
else:
raise ValueError(
'"value" was set {}, but it must be positive only'
.format(value)
)
else:
raise TypeError(
'"value" was set {}, but it must be int only'
.format(type(value))
)
而不是'if else'用'try''去除' – 0TTT0