把可能抛出异常(出错)的语句放在try的block里,然后用except去扑捉(预判)可能的异常类型,如果异常类型match,就执行except模块。
try:
# write some code
# that might throw exception
except <ExceptionType>:
# Exception handler, alert the user比如读取一个不存在的文件会引起IOError,我们就可以提前加以处理。
try:
f = open('nofile.txt', 'r')
print f.read()
f.close()
except IOError:
print 'file not found'file not found执行流程是这样的:
try and except block are executed.except clause will be skipped.try block will be skippedexcept keyword, then the code in that except clause is executed.try:
<body>
except <ExceptionType1>:
<handler1>
except <ExceptionTypeN>:
<handlerN>
except:
<handlerExcept>
else:
<process_else>
finally:
<process_finally>except类似于elif,当try出现异常时,挨个匹配except里的异常类型,如果匹配,执行;若果没有匹配,执行不指定异常类型的except。else只有在try执行时没有异常的时候执行。finally不管try模块是否有异常抛出,都执行。num1, num2 = 1,0
try:
result = num1 / num2
print("Result is", result)
except ZeroDivisionError:
print("Division by zero is error !!")
except:
print("Wrong input")
else:
print("No exceptions")
finally:
print("This will execute no matter what you input")Division by zero is error !!
This will execute no matter what you input用raise语句抛出自己的异常。raise ExceptionClass('Your argument')
def enterage(age):
if age < 0:
raise ValueError("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
try:
num = int(input("Enter your age: "))
enterage(num)
except ValueError:
print 'Only positive integers are allowd'
except:
print 'Something went wrong'Enter your age: -3
Only positive integers are allowd异常参考图,更多异常类型参见官方文档。

exception
有时候我们希望能把异常对象传递给一个变量,也非常方便实现。
try:
# this code is expected to throw exception
except ExceptionType as ex:
# code to handle exceptiontry:
number = int(input("Enter a number: "))
print "The number entered is", number
except NameError as ex:
print "Exception:", exEnter a number: one
Exception: name 'one' is not defined