try:
for item in my_list:
print(my_dictionary[item])
except KeyError as e: #KeyError is the Exception raised when a key is not in a dictionary
print('There is no {} in the dictionary'.format(e.args[0]))
list_ = ["a","b","x"]
assert "x" in list_, "x is not in the list"
print("passed")
#>> prints passed
list_ = ["a","b","c"]
assert "x" in list_, "x is not in the list"
print("passed")
#>>
Traceback (most recent call last):
File "python", line 2, in <module>
AssertionError: x is not in the list
加注:
这种做法有用的两个原因是:
与 try 和 but 块一起使用。提出一个你选择的错误,可以像下面这样自定义,并不会停止脚本,如果你 pass或 continue的脚本; 或者可以是预定义的错误 raise ValueError()
class Custom_error(BaseException):
pass
try:
print("hello")
raise Custom_error
print("world")
except Custom_error:
print("found it not stopping now")
print("im outside")
>> hello
>> found it not stopping now
>> im outside
注意到它没有停止吗? 我们可以使用 but 块中的 exit (1)来停止它。
还可以用于重新引发当前错误,将其传递到堆栈上,以查看是否有其他方法可以处理这个错误。
except SomeError, e:
if not can_handle(e):
raise
someone_take_care_of_it(e)
def validate_email(address):
if not "@" in address:
raise ValueError("Email Addresses must contain @ sign")
然后,在代码的其他地方,您可以调用 valid_ email 函数,如果失败,将抛出一个异常。
try:
validate_email("Mynameisjoe.com")
except ValueError as ex:
print("We can do some special invalid input handling here, Like ask the user to retry the input")
finally:
close_my_connection()
print("Finally always runs whether we succeed or not. Good for clean up like shutting things down.")