python的异常分为两种,1)、语法错误,在python解释器的语法检测中不通过不能运行代码 2)、异常,python程序运行期检测到的错误被称为异常。在没有做异常处理时,将终止程序并提示异常信息,如:①字符串转换为数字时的类型转换异常,②文件读取时的文件不存在异常,③网络链接时主机不可达异常···等。当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。毕竟谁也不希望用着的程序突然的就崩了
1、语法错误
python的语法错误是很多初学者经常遇到的一个问题,这类错误比较低级,只要多敲几遍代码就可以减少这样的错误
>>> if Trur
File "<stdin>", line 1
if Trur
^
SyntaxError: invalid syntax
>>> print("as"))
File "<stdin>", line 1
print("as"))
^
SyntaxError: invalid syntax
如:出现这样的错误就是语法错误,第1行结尾if语句缺少 ":",第6行结尾多了 ")"
2、异常
1)运行期检测到的错误被称为异常,python的语法检测无法检查这样的错误。
>>> int("aa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'aa'
>>> f = open("aaa.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'aaa.txt'
其中第1行,第5行都是出现异常的地方,看一下异常的输出信息,如下图
![](http://imgsrc.baidu.com/forum/w%3D580/sign=bc917cffaa86c91708035231f93c70c6/1f6ef0d7277f9e2f2e53850f1230e924b999f3be.jpg)
2)python的标准异常类
BaseException 为所有异常的基类,Exception 为常规错误的基类
其它python的异常类可以到这里看(http://www.runoob.com/python/python-exceptions.html),就不再一一的述说,也可以百度查看
1、语法错误
python的语法错误是很多初学者经常遇到的一个问题,这类错误比较低级,只要多敲几遍代码就可以减少这样的错误
>>> if Trur
File "<stdin>", line 1
if Trur
^
SyntaxError: invalid syntax
>>> print("as"))
File "<stdin>", line 1
print("as"))
^
SyntaxError: invalid syntax
如:出现这样的错误就是语法错误,第1行结尾if语句缺少 ":",第6行结尾多了 ")"
2、异常
1)运行期检测到的错误被称为异常,python的语法检测无法检查这样的错误。
>>> int("aa")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'aa'
>>> f = open("aaa.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'aaa.txt'
其中第1行,第5行都是出现异常的地方,看一下异常的输出信息,如下图
![](http://imgsrc.baidu.com/forum/w%3D580/sign=bc917cffaa86c91708035231f93c70c6/1f6ef0d7277f9e2f2e53850f1230e924b999f3be.jpg)
2)python的标准异常类
BaseException 为所有异常的基类,Exception 为常规错误的基类
其它python的异常类可以到这里看(http://www.runoob.com/python/python-exceptions.html),就不再一一的述说,也可以百度查看