我对如何使用Try/Exception
和if/else
感到困惑。如果我想告诉用户提供.html
文件,我该如何编写惯用代码?
if url[-4:] ==".html":
// do your things
else:
print('Error! the file is not html file')
我正在检查在这种情况下是否应该使用 try/exception
还是像我做的那样使用 if/else
。
我对如何使用Try/Exception
和if/else
感到困惑。如果我想告诉用户提供.html
文件,我该如何编写惯用代码?
if url[-4:] ==".html":
// do your things
else:
print('Error! the file is not html file')
我正在检查在这种情况下是否应该使用 try/exception
还是像我做的那样使用 if/else
。
try:
# do your thing with `url`
except:
print('Error! the file is not html file')
if
来测试它是没有惯用方法的。 - Paulo Scardinetry:
a = q.get()
try
的意思是尝试这个东西,如果它有效,就使用它,否则except
如果它失败或者出现ValueError
等错误,就使用其他东西。
except:
a = None
更新时间:
try:
url[-4:] == ".html"
except:
print "Error"
try: url[-4:] == ".html"
不会抛出任何异常。 - dom0except
中的 url
没有被重新赋值。但是,在之前的例子中,我已经解释了如何正确使用 try
和 except
,我认为 user3378649 正在寻找这个答案。 - Jonathan Daviesassert url.lower().endswith(".html"), u"the file name must end in .html"
if url.lower().endswith(".html"):
do_your_things_with_url(url)
else:
raise YourCustomException('the url must end in ".html"')
if
测试是很愚蠢的:try:
assert url.lower().endswith(".html")
except AssertionError:
print('Error! url does not end in ".html"')
else:
do_your_things_with_url(url)
if
测试来测试字符串是否以".html"结尾。hasattr
和/或isinstance
进行LBYL测试)。不要过度使用EAFP,特别是如果LBYL相对较便宜-如果廉价的测试可以起作用,为什么要尝试昂贵的操作呢?from bs4 import BeautifulSoup
from html.parser import HTMLParseError
try:
BeautifulSoup(fetched_url_contents)
except HTMLParseError:
print("Error: you haven't given me html!")
MyInputException('Error! the file is not html file')
来触发处理输入错误的代码,而不是“打印”错误信息。 - Paulo Scardine