I am confused on how to use Try/Exception and if/else. How can I write idiomatic code if I want to tell the user to provide .html file
if url[-4:] ==".html":
// do your things
else:
print('Error! the file is not html file')
I am checking whether I should use try/exception in such scenarios or if/else as I did.
In a nutshell:
try:
a = q.get()
try means try this thing, if it works, use it, else except something else if it fails, or it works, and there is an error such as ValueError.
except:
a = None
Updated:
try:
url[-4:] == ".html"
except:
print "Error"
In Python, it's Easier to ask for forgiveness than permission. In other words, the idiomatic way in Python would be to just let the exception be thrown and react accordingly, instead of explicitly checking the condition ("Look before you leap", also in the linked glossary). So your code should look like this:
try:
# do your thing with `url`
except:
print('Error! the file is not html file')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With