Python-异常处理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-异常处理相关的知识,希望对你有一定的参考价值。
一、捕获异常
1、当程序出错时,不会展示bug信息给用户,而是提供一个友好的提示后,继续执行程序
2、如下,实现除法,当分母为0时,捕获并打印出异常信息;Exception可以捕获任何异常
def div(x, y): try: print(x/y) except Exception as e: print(‘异常为‘, e)
>>> div(1,0)
异常为 division by zero
也可以指定异常为ZeroDivisionError
def div(x, y): try: print(x/y) except ZeroDivisionError as e: print(‘异常为‘, e)
>>> div(1,0)
异常为 division by zero
3、同时捕获多个异常
def fdiv(x,y): try: return x/y except TypeError as e: print(‘TypeError: ‘, e) except ZeroDivisionError as e: print(‘ZeroDivisionError: ‘, e) except Exception as e: print(‘其他异常:‘, e)
>>> fdiv(‘ABC‘, 0)
TypeError: unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv(12,0)
ZeroDivisionError: division by zero
也可以用以下方式:
def fdiv1(x,y): try: return x/y except (TypeError, ZeroDivisionError, Exception) as e: print(e)
>>> fdiv1(‘ABC‘, 0)
unsupported operand type(s) for /: ‘str‘ and ‘int‘
>>> fdiv1(12,0)
division by zero
二、常用异常
‘---------------IOError:打开文件路径出错或不存在------------------‘ try: f = open(‘error.txt‘,‘r‘) except IOError as e: print(‘打开文件出错, 错误信息:‘, e) ‘--------------ImportError:导入模块路径出错或不存在--------------‘ try: import error except ImportError as e: print(‘导入模块出错, 错误信息:‘, e) ‘--------------IndexError:索引出界----------------------------‘ list1 = [1,2,3,4,5,6] try: print(list1[6]) except IndexError as e: print(‘查询列表出错, 错误信息:‘, e) ‘----------------keyError:查找字典中不存在的关键字---------------‘ dict1 = {1:‘A‘, 2:‘B‘} try: print(dict1[3]) except KeyError as e: print(‘查询字典出错, 错误信息:‘, e) ‘----------------TypeError:参数类型不匹配----------------------‘ def fint(a): print(a/2) try: str1 = ‘ABC‘ fint(str1) except TypeError as e: print(‘参数类型出错, 错误信息:‘, e) ‘------------ValueError:参数类型匹配,但是传入的值不对------------‘ str1 = ‘ABC‘ try: print(int(str1)) except ValueError as e: print(‘参数值出错, 错误信息:‘, e) ‘------------------NameError:使用的变量没有赋值------------------‘ try: print(a) except NameError as e: print(‘参数出错, 错误信息:‘, e)
三、自定义异常
class MyException(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: raise MyException(‘自定义异常‘) except MyException as e: print(e)
四、主动抛出异常
try: raise IOError(‘读写文件出错了‘) #主动抛出IOError异常 except IOError as e: print(e)
五、try - except - else - finally
try: f = open(‘test.txt‘, ‘r‘) except IOError as e: #打开文件失败,则抛出异常 print(e) else: #打开文件成功,则执行else块 print(‘执行else‘) f.close() finally: #无论文件是否正常打开,都会执行finally块 print(‘执行finally‘)
以上是关于Python-异常处理的主要内容,如果未能解决你的问题,请参考以下文章
在 Python 多处理进程中运行较慢的 OpenCV 代码片段