在python中处理错误的最有效方法是什么?

时间:2017-10-10 01:21:34

标签: python error-handling try-catch assertion isinstance

我是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))
    )

2 个答案:

答案 0 :(得分:2)

您可以尝试像这样写

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

答案 1 :(得分:2)

反转您的逻辑以简化您的代码:

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 not isinstance(value, int):
        raise TypeError('"value" was set {}, but it must be int only'.format(type(value)))
    if value < 0:
        raise ValueError('"value" was set {}, but it must be positive only'.format(value))
    if not isinstance(pos, int):
        raise TypeError('"pos" was set {}, but it must be int only'.format(type(pos)))
    # and so on...

    # once you finish all your checks, then do what you planned to do

由于raise将自动取消执行函数的其余部分,因此在条件引发之后出现的任何代码都可以认为该条件不适用,因此您不需要else语句。