Should I always specify an exception type in `except` statements?

前端 未结 7 1110
广开言路
广开言路 2020-11-22 15:33

When using PyCharm IDE the use of except: without an exception type triggers a reminder from the IDE that this exception clause is Too broad.

相关标签:
7条回答
  • 2020-11-22 16:12

    Not specfic to Python this.

    The whole point of exceptions is to deal with the problem as close to where it was caused as possible.

    So you keep the code that could in exceptional cirumstances could trigger the problem and the resolution "next" to each other.

    The thing is you can't know all the exceptions that could be thrown by a piece of code. All you can know is that if it's a say a file not found exception, then you could trap it and to prompt the user to get one that does or cancel the function.

    If you put try catch round that, then no matter what problem there was in your file routine (read only, permissions, UAC, not really a pdf, etc), every one will drop in to your file not found catch, and your user is screaming "but it is there, this code is crap"

    Now there are a couple of situation where you might catch everything, but they should be chosen consciously.

    They are catch, undo some local action (such as creating or locking a resource, (opening a file on disk to write for instance), then you throw the exception again, to be dealt with at a higher level)

    The other you is you don't care why it went wrong. Printing for instance. You might have a catch all round that, to say There is some problem with your printer, please sort it out, and not kill the application because of it. Ona similar vain if your code executed a series of separate tasks using some sort of schedule, you wouldnlt want the entire thing to die, because one of the tasks failed.

    Note If you do the above, I can't recommend some sort of exception logging, e.g. try catch log end, highly enough.

    0 讨论(0)
提交回复
热议问题