目录
1.1、ZeroDivisionError(除以0,会发生异常)
1.2、NameError(使用未赋值的变量,发生名字异常)
1.3、TypeError(两个变量类型不一致,相加等操作发生类型异常)
1.4、 ValueError(字符串类型转换整型,发生值异常)
第一章、异常分类
参考http://www.shareblogs.top/304/
异常的种类很多,这里只罗列常见的几种类型
1.1、ZeroDivisionError(除以0,会发生异常)
10 * (1/0)
输出结果:
C:\Users\lanmage2\test1\Scripts\python.exe F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py
Traceback (most recent call last):
File "F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py", line 567, in <module>
10 * (1/0)
ZeroDivisionError: division by zero
Process finished with exit code 1
1.2、NameError(使用未赋值的变量,发生名字异常)
4 + aaa*3
输出结果:
C:\Users\lanmage2\test1\Scripts\python.exe F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py
Traceback (most recent call last):
File "F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py", line 567, in <module>
4 + aaa*3
NameError: name 'aaa' is not defined
Process finished with exit code 1
1.3、TypeError(两个变量类型不一致,相加等操作发生类型异常)
'100' + 2000
输出结果:
C:\Users\lanmage2\test1\Scripts\python.exe F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py
Traceback (most recent call last):
File "F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py", line 568, in <module>
'100' + 2000
TypeError: can only concatenate str (not "int") to str
Process finished with exit code 1
1.4、 ValueError(字符串类型转换整型,发生值异常)
比如下面输入字符aaa,就不能转转换为整数,那么发生下面异常。
while True:
try:
x = int(input("Please enter a number: "))
print(x)
break
except ValueError:
print("Oops! That was no valid number. Try again ")
C:\Users\lanmage2\test1\Scripts\python.exe F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py
Please enter a number: aaa
Oops! That was no valid number. Try again
Please enter a number:
1.5、OSError(没找到文件,发生OS异常)
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
输出结果:
C:\Users\lanmage2\test1\Scripts\python.exe F:/百度云同步盘/我的学习/18、python/test1/View/FileTwo.py
OS error: [Errno 2] No such file or directory: 'myfile.txt'
Process finished with exit code 0
1.6、IOError
第二章、异常处理
2.1、常规的异常处理
异常的结构如下,异常处理类似于C#的try...cacth。所以异常的的处理,在except里面处理即可。
try:
psss
except :
psss
else:
pass
或者
try:
psss
except :
psss
或者
try:
psss
except 异常类型1:
psss
except 异常类型2:
psss
except 异常类型3:
psss
2.2、自定义异常
请参考https://www.runoob.com/python3/python3-errors-execptions.html