Reputation: 459
E.g. 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.
Upvotes: 6
Views: 1816
Reputation: 1967
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,
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.
Upvotes: 4
Reputation: 117681
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.
Upvotes: 5