>>> 10 * (1/0) # 0 不能作为除数,触发异常
Traceback (most recent call last):
File "" , line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3 # spam 未定义,触发异常
Traceback (most recent call last):
File "" , line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2 # int 不能与 str 相加,触发异常
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: can only concatenate str (not "int") to str
1)使用 try/except 进行异常处理的语法:
try:
可能存在异常的代码块
except errorType1:
发生异常1时执行的代码块
except errorType1:
发生异常2时执行的代码块
……
except errorTypen:
发生异常n时执行的代码块
while True:
try:
x = int(input("请输入一个数字: "))
break
except ValueError:
print("您输入的不是数字,请再次尝试输入!")
2)try/except 语句的工作方式:
except (RuntimeError, TypeError, NameError):
代码块
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
try:
可能存在异常的代码块
except errorType1:
发生异常1时执行的代码块
except errorType1:
发生异常2时执行的代码块
……
except errorTypen:
发生异常n时执行的代码块
else:
try 代码块执行完,没有异常时,执行的代码块
# 在 try 语句中判断文件是否可以打开,如果打开文件时正常的没有发生异常则执行 else 部分的语句,读取文件内容
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero
try:
可能存在异常的代码块
except errorType1:
发生异常1时执行的代码块
except errorType1:
发生异常2时执行的代码块
……
except errorTypen:
发生异常n时执行的代码块
else:
try 代码块执行完,没有异常时,执行的代码块
finally:
执行完前面那一堆之后,继续执行这一个代码块
raise [Exception [, args [, traceback]]]
# 如果 x 大于 5 就触发异常
x = 10
if x > 5:
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
'''
输出结果:
Traceback (most recent call last):
File "test.py", line 3, in
raise Exception('x 不能大于 5。x 的值为: {}'.format(x))
Exception: x 不能大于 5。x 的值为: 10
'''
>>> try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "" , line 2, in ?
NameError: HiThere
>>> class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
>>> try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "" , line 1, in ?
__main__.MyError: 'oops!'
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
# 如果在调用 write 的过程中,出现了异常,则 close 方法将无法被执行,因此资源就会一直被该程序占用而无法被释放
file = open('./test.txt', 'w')
file.write('hello world !')
file.close()
# 对可能发生异常的代码处进行 try 捕获,发生异常时执行 except 代码块,finally 代码块是无论什么情况都会执行,所以文件会被关闭,不会因为执行异常而占用资源。
file = open('./test.txt', 'w')
try:
file.write('hello world')
finally:
file.close()
# 使用 with 关键字系统会自动调用 f.close() 方法, with 的作用等效于 try/finally 语句是一样的
with open('./test.txt', 'w') as file:
file.write('hello world !')
# 查看文件是否关闭
>>> f.closed
True