1. try-except 语句
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError as error:
print('打开文件出错\n原因是:' + str(error))
# 打开文件出错
# 原因是:[Errno 2] No such file or directory: 'test.txt'
try:
f = open('test.txt')
print(f.read())
f.close()
except OSError:
print('打开文件出错')
2.try - except - finally 语句
finally--无论如何都会被执行的代码
def divide(x, y):
try:
result = x / y
print("result is", result)
except ZeroDivisionError:
print("division by zero!")
finally:
print("executing finally clause")
divide(2, 1)
# result is 2.0
# executing finally clause
divide(2, 0)
# division by zero!
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'
3. try-except - else 语句
else--如果没有异常执行这块代码(一定要跟着except)
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print("Error: 没有找到文件或读取文件失败")
else:
print("内容写入文件成功")
fh.close()
4. raise语句
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
# An exception flew by!