Python: How can I know which exceptions might be thrown from a method call

前端 未结 7 1318
感情败类
感情败类 2020-11-28 05:43

Is there a way knowing (at coding time) which exceptions to expect when executing python code? I end up catching the base Exception class 90% of the time since I don\'t kno

7条回答
  •  暖寄归人
    2020-11-28 06:02

    The correct tool to solve this problem is unittests. If you are having exceptions raised by real code that the unittests do not raise, then you need more unittests.

    Consider this

    def f(duck):
        try:
            duck.quack()
        except ??? could be anything
    

    duck can be any object

    Obviously you can have an AttributeError if duck has no quack, a TypeError if duck has a quack but it is not callable. You have no idea what duck.quack() might raise though, maybe even a DuckError or something

    Now supposing you have code like this

    arr[i] = get_something_from_database()
    

    If it raises an IndexError you don't know whether it has come from arr[i] or from deep inside the database function. usually it doesn't matter so much where the exception occurred, rather that something went wrong and what you wanted to happen didn't happen.

    A handy technique is to catch and maybe reraise the exception like this

    except Exception as e
        #inspect e, decide what to do
        raise
    

提交回复
热议问题