简体   繁体   中英

When Should I Use a Try-Except statement in Python?

Eg If I am trying to open a file, can I not simply check if os.path.exists(myfile) instead of using try/except . I think the answer to why I should not rely on os.path.exists(myfile) is that there may be a number of other reasons why the file may not open.

Is that the logic behind why error handling using try/except should be used?

Is there a general guideline on when to use Exceptions in Python.

Race conditions.

In the time between checking whether a file exists and doing an operation that file might have been deleted, edited, renamed, etc...

On top of that, an exception will give you an OS error code that allows you to get more relevant reason why an operation has failed.

Finally, it's considered Pythonic to ask for forgiveness, rather than ask for permission.

Generally you use try/except when you handle things that are outside of the parameters that you can influence.

Within your script you can check variables for type, lists for length, etc. and you can be sure that the result will be sufficient since you are the only one handling these objects. As soon however as you handle files in the file system or you connect to remote hosts etc. you can neither influence or check all parameters anymore nor can you be sure that the result of the check stays valid.

As you said,

  • the file might be existent but you don't have access rights
  • you might be able to ping a host address but a connection is declined

There are too many factors that could go wrong to check them all seperately plus, if you do, they might still change until you actually perform your command.

With the try/error you can generally catch every exception and handle the most important errors individually. You make sure that the error is handled even if the test succeeds at first but fails after you start running your commands.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM