try,except语句是Python中处理异常的常用语句。
异常
异常就是程序中使程序无法继续运行的报错。通常,异常别分为两类:语法异常(SyntaxError)和程序异常(Exception),程序异常又被分为以下几类:
- KeyError:通常由于访问字典中不存在的键;
- ValueError:通常由于访问字典中不存在的值;
- FileNotFoundError:通常由于访问路径中不存在的文件;
- TypeError:通常由于数据类型与操作不兼容;
- IndexError:通常由于访问不存在的序列;
- OverflowError:通常由数值溢出;
- AttributeError:通常操作不存在的属性;
try-except
try-expect结构的用法类似于if-elif结构。在try语句之后,加入可能出现报错的代码(假设为block1)。在except语句后加入block1出现异常A后会运行的代码(假设为block2)。如果程序中的block1正常运行,则block2不会被运行;如果block1出现异常A,则跳过block1运行block2。如果except后没有指定异常,则默认处理所有的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。
try:
i+1
print(i) #block1
except:
i=2
i+=1
print(i) #block2
示例:判断用户输入的是否是数字。
while True:
a=input('Please enter a number: ')
try:
a=float(a) #只有输入值能被转化为浮点数时运行
print('Your number is',a) #
except:
print('That\'s not a number')
print('Over')
当然,try-except语句也可以用来处理特定类型的异常。
my_info={'age':18,'weight':130,'height':'very very tall'}
try:
print(my_info['IQ'])
except KeyError:
print('Ooops, that\'s a KeyError!')
expect可以有不止一个。我们可以依此来判断异常的类型。已知这段代码无法正常工作,但未知异常原因。
my_info={'age':18,'weight':130,'height':'very very tall'}
print(my_info['IQ'])
可以添加不同的except语句以判断异常类型。
my_info={'age':18,'weight':130,'height':'very very tall'}
try:
print(my_info['IQ'])
except KeyError:
print('Ooops, that\'s a KeyError!')
except ValueError:
print('Ooops, that\'s a ValueError!')
except FileNotFoundError:
print('Ooops, that\'s a FileNotFoundError!')
except IndexError:
print('Ooops, that\'s a IndexError!')
运行程序可得,出现了KeyError。
try-except-else
在程序没有报错时,else中的语句会被执行。
my_info={'age':18,'weight':130,'height':'very very tall'}
try:
print(my_info['age'])
except KeyError:
print('Ooops, that\'s a KeyError!')
else:
print('完美')
try-finally
finally语句中的内容无论是否出错都会运行。
my_info={'age':18,'weight':130,'height':'very very tall'}
try:
print(my_info['Hobby'])
except KeyError:
print('Ooops, that\'s a KeyError!')
finally:
print('结束')
qTNlGLW6SBw
I eagerly anticipate your fresh and unique perspectives. It keeps me coming back for more.
The article is very informative. Thanks for sharing your insights and ideas with your readers.
Heya i’m for the primary time here. I found this board
and I find It really helpful & it helped me out a lot.
I hope to offer one thing back and aid others such as you aided
me.
Your writing has a lively quality that creates clear images in my mind. I can easily visualize every aspect you describe.
Your enthusiasm is truly contagious, making it impossible not to become enthusiastic about the topics you explore.
GQHsC6iiuuM
I appreciate the style you present complex ideas in a simple and accessible way.
It is not my first time to pay a visit this website, i
am browsing this web site dailly and obtain fastidious facts from here daily.
Your zeal is infectious. It is challenging not to become enthused about the topics you explore.
The article is fantastic. I loved reading it. Thanks for posting such a great post.
Your post is an eye-opener. I didn’t realize of those before. Thanks for educating me.
Your blog illuminates my day like a beam of light. Thank you for spreading positivity with your words.
This post is a gem that deserves to be shared with a broader audience.
I enjoyed reading this article and discovered some new perspectives on the topic. Thanks for sharing your insights.
I’m constantly on the lookout for top-notch content and this is one of them.
I constantly look forward to your latest and distinctive takes. It keeps me returning for more.
We’re a gaggle of volunteers and starting a new scheme in our community.
Your site offered us with useful information to work on. You have performed
a formidable process and our whole neighborhood will be thankful to you.
Your blog never fails to captivate me. It’s like entering a new dimension.
Your blog entrances me from beginning to end. I can’t merely leave without absorbing your whole post.