Friday, July 20, 2018

Python if statement error handling










I am kind of a beginner learning python, but I got this bit of code that I want to handle in a way if someone was too enter an invalid path that does not exists like Z:\ instead of C:\ I want it to raise some sort of error, now I know how to go about doing it, I just do not know how to check if it will be invalid? like how can I make my code check if that drive or path exist on this PC before it creates the path, is there a way to do that in python?




website_path = input("\nEnter the absolute path for your website: ")


any advice would be great, thanks.


Answer



The Pythonic way of handling this is to "ask forgiveness, not permission": just try to perform whatever operation you were going to on the path you get (like opening files) and let the functions you're calling raise the appropriate exception for you. Then use exception handling to make the error messages more user friendly.



That way, you'll get all the checks done just in time. Checking beforehand is unreliable; what if you check whether a file exists, just before some other process deletes it?


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...