1. 一个例子
file_name = input('请输入要打开的文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
print(each_line)
# 由于未输入文件后缀而报错
请输入要打开的文件名:girl_1
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-92806aeac0ba> in <module>()
1 file_name = input('请输入要打开的文件名:')
----> 2 f = open(file_name)
3 print('文件的内容是:')
4 for each_line in f:
5 print(each_line)
FileNotFoundError: [Errno 2] No such file or directory: 'girl_1'
2. 异常种类
以下是 Python 内置异常类的层次结构:
'''
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
'''
3. AssertionError
# python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。
my_list = ['小甲鱼是帅哥']
assert len(my_list) > 0
my_list.pop()
'小甲鱼是帅哥'
assert len(my_list) > 0
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-9-c183f6b56427> in <module>()
----> 1 assert len(my_list) > 0
AssertionError:
4. AttributeError
# 访问未知的属性或方法
my_list.fishc
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-6cd380373ff6> in <module>()
----> 1 my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
5. IndexError
# 索引不存在
my_list = [1,2,3]
my_list[3]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-12-630619d25352> in <module>()
1 # 索引不存在
2 my_list = [1,2,3]
----> 3 my_list[3]
IndexError: list index out of range
6.KeyError
# 关键字不存在
my_dict = {'one':1,'two':2,'three':3}
print(my_dict['one'])
print(my_dict['four'])
1
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-17-5fd29812ea8d> in <module>()
2 my_dict = {'one':1,'two':2,'three':3}
3 print(my_dict['one'])
----> 4 print(my_dict['four'])
KeyError: 'four'
7.NameError
# 访问一个不存在的变量
print(fishc)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-cfe17886c343> in <module>()
1 # 访问一个不存在的变量
----> 2 print(fishc)
NameError: name 'fishc' is not defined
8. OSError
# 如第一个例子FileNotFoundError就是它的子类
9. SyntaxError
# 语法错误
print 'I love you'
File "<ipython-input-18-3552d36a503f>", line 2
print 'I love you'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('I love you')?
10. TypeError
# 不同类型间的无效操作
print(1 + '1')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-27cba25553e1> in <module>()
1 # 不同类型间的无效操作
----> 2 print(1 + '1')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
11. ZeroDivisionError
# 除数为0
print(5/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-21-fb41e7d29eb0> in <module>()
1 # 除数为0
----> 2 print(5/0)
ZeroDivisionError: division by zero
12. 异常检测——try-except
# 语法
'''
try:
检测范围
except Exception[as reason]:
出现异常(Exception)后的处理代码
'''
报错
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-22-a3241d9cac63> in <module>()
----> 1 ff = open('我为什么是一个文件.txt')
2 print(ff.read())
3 ff.close()
FileNotFoundError: [Errno 2] No such file or directory: '我为什么是一个文件.txt'
捕获异常并给出提示
try:
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except OSError:
print('文件出错啦!!')
文件出错啦!!
捕获异常并给出错误原因
try:
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except OSError as reason:
print('文件出错啦!!')
print('错误的原因是:' + str(reason))
文件出错啦!!
错误的原因是:[Errno 2] No such file or directory: '我为什么是一个文件.txt'
有多个异常
# 只捕获第一个异常,因为程序运行到第一个异常就会停止运行
try:
sum = 1 + '1'
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except OSError as reason:
print('文件出错啦!!')
print('错误的原因是:' + str(reason))
except TypeError as reason:
print('类型出错啦!!')
print('错误的原因是:' + str(reason))
类型出错啦!!
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
# 若未捕获相应类型的异常,仍会报错
try:
int('abc')
sum = 1 + '1'
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except OSError as reason:
print('文件出错啦!!')
print('错误的原因是:' + str(reason))
except TypeError as reason:
print('类型出错啦!!')
print('错误的原因是:' + str(reason))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-23ae102eaf21> in <module>()
1 # 若未捕获相应类型的异常,仍会报错
2 try:
----> 3 int('abc')
4 sum = 1 + '1'
5 ff = open('我为什么是一个文件.txt')
ValueError: invalid literal for int() with base 10: 'abc'
无法确定确切的类型
# 可以直接给出提示
try:
int('abc')
sum = 1 + '1'
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except:
print('出错啦!')
出错啦!
# 也可以根据可能的类型来给出提示
try:
sum = 1 + '1'
ff = open('我为什么是一个文件.txt')
print(ff.read())
ff.close()
except (OSError,TypeError):
print('出错啦!!')
13. 异常检测——try-finally
# 语法
'''
try:
检测范围
except Exception [as reason]:
出现异常(EXception)后的处理代码
finally:
无论如何都会被执行的代码
'''
try:
ff = open('我是一个文件.txt','w')
print(ff.write('我存在了!'))
sum = 1 + '1'
ff.close()
except (OSError,TypeError):
print('出错啦!!')
# 由于在创建这个文件之后出现了异常,而文件还未关闭,即文件未保存,则文件未写入任何东西
# 会打印出准备写入字符的个数
5
出错啦!!
try:
ff = open('我是一个文件.txt','w')
print(ff.write('我存在了!'))
sum = 1 + '1'
except (OSError,TypeError):
print('出错啦!!')
finally:
# 这里写入关闭文件的操作,无论程序怎么报错,都会执行这里
ff.close()
5
出错啦!!
总结:程序出现异常时,会先执行except里的语句,然后执行finally里的语句
14. 引出异常——raise
# 直接
raise
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-35-9c9a2cba73bf> in <module>()
----> 1 raise
RuntimeError: No active exception to reraise
raise ZeroDivisionError
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-36-c62fc6984c64> in <module>()
----> 1 raise ZeroDivisionError
ZeroDivisionError:
raise ZeroDivisionError('除数为0的异常')
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-38-bec5ebf736a5> in <module>()
----> 1 raise ZeroDivisionError('除数为0的异常')
ZeroDivisionError: 除数为0的异常