try:
表达式 1(如果表达式可以成功执行,则执行,执行后跳到 finally 语句)
except ExpectErrorType, Argument: (表达式1 没有做成功,且正好是 ExpectErrorType 的错误情况,则执行)
表达式2 (如何处理这种异常情况)
else: (try succ && 上面 except 语句任一满足 )之外的情况处理方法
.....
finally:(可以不要)
.... 无论什么情况都会的处理
失败乃成功之母
1.语法错误(syntax errors):
SyntaxError: invalid syntax:查询语法无效
例:
>>> for i in range(10)
File "<stdin>", line 1 #显示位置
for i in range(10) #显示位置
^
SyntaxError: invalid syntax #报错原因
2.异常
>>> 1/0
Traceback (most recent call last): #追溯最近一次报错
File "<stdin>", line 1, in <module> #显示位置
ZeroDivisionError: integer division or modulo by zero #报错原因
汇总:
异常 描述
NameError 尝试访问一个没有申明的变量
ZeroDivisionError 除数为0
SyntaxError 语法错误
IndexError 索引超出序列范围
KeyError 请求一个不存在的字典关键字
IOError 输入输出错误(比如你要读的文件不存在)
AttributeError 尝试访问未知的对象属性
TypeError 不是可执行的数据类型
实例1:输入两个数字,若第二个数字为0,则报错
while 1:
print "this is a division program."
c = raw_input("input 'c' continue, otherwise Sign out:") #输入'c'进行下一步
if c == 'c':
a = raw_input("first number:")
b = raw_input("second number:")
try: #无报错,执行下一步,若报错,跳过下一步
print float(a)/float(b)
print """*************************
"""
except ZeroDivisionError: #报错,执行下一步
print "The second number can't be zero!"
print """*************************
"""
else:
break
实例2:如果没有触发报错,就执行else的语句
try:
print('I am sure no exception is going to occur!')
except Exception:
print('exception')
else:
# 这里的代码只会在try语句里没有触发异常时运行,
# 但是这里的异常将 *不会* 被捕获
print('This would only run if no exception occurs. And an error here '
'would NOT be caught.')
finally:
print('This would be printed in every case.')
# Output: I am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would be printed in every case.