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

标签 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))
    )

最佳答案

你可以试试这样写

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

关于python - 在 python 中处理错误的最有效方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657279/

相关文章:

python - 'virtualenv' 'pip install sqlalchemy' 但 'pip list' 看不到

Python复制和连接链表,保持顺序

android - 应用程序级别错误

error-handling - Apache camel 错误处理如何处理多播和事务

scala - 为什么 Scala 的 Try 没有异常类型的类型参数?

loops - Powershell try catch 并重试?

python - Lambda 未加载加密共享库

python - matplotlib x 轴上日期之间的 vlines

python - 这个简单的脚本不起作用

Python - peewee - 调试语句 - 错误记录在哪里