Python之异常处理-Exception

时间:2023-03-10 02:04:23
Python之异常处理-Exception

在写python程序时, 不要害怕报错, 也不要怕自己的英语不够好, 不要看到一有红色的字就心里发怂. 其实报的错也是有套路可寻滴~识别了异常的种类, 才能对症下药.

常见异常:

Exception                        所有异常的基类

AttributeError                 特性应用或赋值失败时引发

IOError                             试图打开不存在的文件时引发

IndexError                       在使用序列中不存在的索引时引发

KeyError                          在使用映射不存在的键时引发

NameError                       在找不到名字(变量)时引发

SyntaxError                     在代码为错误形式时引发

TypeError                         在内建操作或者函数应用于错误类型的对象是引发

ValueError                       在内建操作或者函数应用于正确类型的对象,但是该对象使用不合适的值时引发

ZeroDivisionError          在除法或者摸除操作的第二个参数为0时引发

1. 抛出异常

Python之异常处理-Exception
def div(x,y):
if y == 0:
raise ZeroDivisionError('Zero is not allowed.')
return x/y try:
div(4,0)
except Exception as e:
print(e)
Python之异常处理-Exception
Zero is not allowed.

Process finished with exit code 0

2. 捕捉异常:
可同时捕捉多个异常,可捕捉异常对象,可忽略异常类型以捕捉所有异常

Python之异常处理-Exception
try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',x/y)
except ZeroDivisionError: #捕捉除0异常
print("ZeroDivision")
except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
Python之异常处理-Exception
input x:3
input y:0
ZeroDivision Process finished with exit code 0
input x:5
input y:a
invalid literal for int() with base 10: 'a' Process finished with exit code 0

try/except 可以加上 else 语句,实现在没有异常时执行什么

Python之异常处理-Exception
try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',x/y)
except ZeroDivisionError: #捕捉除0异常
print("ZeroDivision")
except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
else: #没有异常时执行
print('it works well')
Python之异常处理-Exception
Python之异常处理-Exception
input x:4
input y:2
x/y = 2.0
it works well Process finished with exit code 0
Python之异常处理-Exception

3. finally 语句
不管是否出现异常,最后都会执行finally的语句块内容,用于清理工作
所以,你可以在 finally 语句中关闭文件,这样就确保了文件能正常关闭

Python之异常处理-Exception
try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',x/y)
except ZeroDivisionError: #捕捉除0异常
print("ZeroDivision")
except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
else: #没有异常时执行
print('it works well')
finally: #不管是否有异常都会执行
print("Cleaning up")
Python之异常处理-Exception
Python之异常处理-Exception
input x:4
input y:a
invalid literal for int() with base 10: 'a'
Cleaning up Process finished with exit code 0
Python之异常处理-Exception

异常抛出之后,如果没有被接收,那么程序会抛给它的上一层,比如函数调用的地方,要是还是没有接收,那继续抛出,如果程序最后都没有处理这个异常,那它就丢给操作系统了 -- 你的程序崩溃了