异常处理是提高程序稳定、可靠的一个重要因素,笔者最近整理了下一常用的python异常处理方法,以及使用案例,记录在此处以便后续查阅。
功能
包括raise、try except两中常见异常处理方法,具体包括ValueError、OSError、TypeError、IndexError、KeyError、AttributeError、ZeroDivisionError、NameError、IOError等
代码
python源码如下:
#!/usr/bin/python
# -*- coding:utf-8 -*-
import math
def raise_func1(x):
# def sqrt(x):
if not isinstance(x, (int, float)):
raise TypeError( 'x must be numeric ' )
elif x < 0:
raise ValueError( 'x cannot be negative ')
else:
print(math.sqrt(x))
def error_func1():
'''
ValueError
'''
while True:
try:
x = int(input('input x:'))
print('x = ' + str(x))
break
except ValueError:
print('Not valid input')
def error_func2():
'''
OSError
ValueError
'''
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
print('i= '+str(i))
except OSError as err:
print('os error: {0}'.format(err))
except ValueError:
print('Could not convert data to an integer.')
def error_func3(x):
'''
TypeError
'''
try:
y = abs(x)
print('abs({0})={1}'.format(x,y))
except TypeError as err:
print('type error: {0}'.format(err))
def error_func4(index):
'''
IndexError
'''
int_list = [0,1,2,3,4,5]
try:
value = int_list[index]
print('int_list[{0}] = {1}'.format(index,value))
except IndexError as err:
print('index error: {0}'.format(err))
def error_func5(name):
'''
KeyError
'''
str_dict = {'a':1, 'b':2}
try:
value = str_dict[name]
print('str_dict[{0}] = {1}'.format(name,value))
except KeyError as err:
print('key error: {0}'.format(err))
def error_func6():
'''
AttributeError
'''
int_list = [1,2,3]
try:
value = int_list.what
value = int_list.count
print(value)
except AttributeError as err:
print('attribute error: {0}'.format(err))
def error_func7(x):
'''
ZeroDivisionError
'''
try:
y = 6 / x
print(y)
except ZeroDivisionError as err:
print('ZeroDivision Error: {0}'.format(err))
def error_func8():
'''
NameError
'''
try:
print(x)
except NameError as err:
print('Name Error: {0}'.format(err))
def error_func9(filename):
'''
IOError
'''
try:
f = open(filename)
f.close()
except IOError as err:
print('IO Error: {0}'.format(err))
def error_func10(filename):
'''
with Exception, catch all kinds of error!
'''
try:
with open(filename,'r') as f:
str_list = f.readlines()
print(str_list)
except Exception as e:
print('different err:',e)
def error_functions():
others = 'EOFError,KeyboardInterrupt,StopIteration,SyntaxError,SystemError'
print('other error, including '+others)
if __name__ == '__main__':
# raise_func1(-5)
# error_func1()
# error_func2()
# error_func3(-5) #'abc'
# error_func4(0) # 8
# error_func5('a') # 'c'
# error_func6()
# error_func7(6) # 0
# error_func8()
error_func9('IO.txt')
error_func10('IO.txt')
error_functions()
通过 traceback 来输出报错的堆信息
#!/usr/bin/python3
# -*- coding:utf-8 -*-
import traceback
def get_error_info():
try:
a = 5
b = 0
print(a/b)
except Exception as e:
print(e)
print(traceback.format_exc())
if __name__== '__main__':
get_error_info()
"""
输出结果:
division by zero
Traceback (most recent call last):
File "/home/xg/files/code/gitlab/xgdoc/code/tmp/20221201-test-log/app.py", line 10, in get_error_info
print(a/b)
ZeroDivisionError: division by zero
"""
说明
笔者测试系统为Ubuntu1910,Python3.7.