python异常处理
异常处理
异常就是程序运行时发生错误的信号,也就是我们常说的报错
报错分为两种
调试和错误
调试是指程序员在写代码的时候出现了错误,进行修改
错误是指程序在运行的过程中,我们哪方面没有考虑到,出现了错误
万能异常
try:
a=1/0
except Exception as e:
print(e)
结果是
division by zero
万能异常和其他异常相结合
万能异常放最下面
try:
name
import a
a=1/0
except IndexError as e3:
print(e3)
except NameError as e2:
print(e2)
except SyntaxError as e:
print(e)
except Exception as e1:
print(e1)
else程序没有报错,就执行else里面的程序
try:
a=1/1
except Exception as e1:
print(e1)
else:
print('执行else')
结果是
执行else
finally不管程序是否出错都会运行finally
try:
name
import a
a=1/0
except IndexError as e3:
print(e3)
except NameError as e2:
print(e2)
except SyntaxError as e:
print(e)
except Exception as e1:
print(e1)
else:
print('执行else')
finally:
print('执行finally')
结果是
name 'name' is not defined
执行finally
raise主动抛出异常
try:
a=1/0
except Exception:
print('抛出异常')
raise
结果是
抛出异常
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\test.py", line 2, in <module>
a=1/0
ZeroDivisionError: division by zero
自定义异常
class EvaException(Exception):
def __init__(self,msg):
self.msg=msg
raise EvaException('这是一个自定义的错误')
结果是
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\test.py", line 6, in <module>
raise EvaException('这是一个自定义的错误')
__main__.EvaException: 这是一个自定义的错误

浙公网安备 33010602011771号