每当发生让Python不知所措的错误时,它都会创建一个异常对象,。如果你编写了处理该异常的代码,程序将继 续运行;如果你未对异常进行处理,程序将停止,并显示一个traceback,其中包含有关异常的报告
1.使用try-except代码块
try:
print(5/0)
except ZeroDivisionError:
print("you can't divide by zero")
2.使用异常避免崩溃
try-except-else 代码块
print("Give me two numbers,and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number=input('\nFirst number: ')
if first_number == 'q':
break
second_number = input('\nsecond_number: ')
try:#只有可能引发异常的代码才需要放在try 语句中
answer = int(first_number)/int(second_number)
except ZeroDivisionError:#except 代码块告诉Python,如果它尝试运行try 代码块中的代码时引发了指定的异常,该怎么办
print("You can't divide by zero")
else:#仅在try 代码块成功 执行时才需要运行的代码应放在else 代码块中
print(answer)
3.文件找不到的或者文件名不正确,这样的情况也是使用try-except
filename='miss.txt'
try:
with open(filename) as m_obj:
contents = m_obj.read()
except FileNotFoundError:
msg="Sorry, the file " + filename + " does not exist."
print(msg)
4.想要失败的时候“一声不吭”
filename='miss.txt'
try:
with open(filename) as m_obj:
contents = m_obj.read()
except FileNotFoundError:
pass#出现FileNotFoundError 异常时,将执行except 代码块中的代码,但什么都不会发生,不会出现traceback,也没有任何输出
else:
网友评论