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

前端 未结 7 1311
感情败类
感情败类 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 05:57

    normally, you'd need to catch exception only around a few lines of code. You wouldn't want to put your whole main function into the try except clause. for every few line you always should now (or be able easily to check) what kind of exception might be raised.

    docs have an exhaustive list of built-in exceptions. don't try to except those exception that you're not expecting, they might be handled/expected in the calling code.

    edit: what might be thrown depends on obviously on what you're doing! accessing random element of a sequence: IndexError, random element of a dict: KeyError, etc.

    Just try to run those few lines in IDLE and cause an exception. But unittest would be a better solution, naturally.

提交回复
热议问题