学习Python 十二 (异常)
2021/4/24 1:25:16
本文主要是介绍学习Python 十二 (异常),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
14.异常
14.1 什么是异常
异常:正常的情况,运行程序的过程中出现问题,BUG(错误不一定是异常)
14.2 处理异常
try代码块
try: #放的是有可能造成异常的代码 except: #处理异常
如:
try: num = int(input('输入一个数:')) result= num+11 except Exception as e: print('出现异常') print('在这里处理异常',e) num=int(input('重新输入一个数:')) result=num+11 print(result) print('结束')
常见的异常:
import builtins
dir(builtins)
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BlockingIOError’,
‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’, ‘ChildProcessError’, ‘ConnectionAbortedError’,
‘ConnectionError’, ‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’,
‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’, ‘FileExistsError’, ‘FileNotFoundError’,
‘FloatingPointError’, ‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’,
‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’, ‘KeyError’,
‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘ModuleNotFoundError’, ‘NameError’, ‘None’,
‘NotADirectoryError’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’,
‘PendingDeprecationWarning’, ‘PermissionError’, ‘ProcessLookupError’, ‘RecursionError’,
‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StopAsyncIteration’,
‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’,
‘TimeoutError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’,
‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’,
‘ValueError’, ‘Warning’, ‘WindowsError’, ‘ZeroDivisionError’, ‘build_class’, ‘debug’, ‘doc’, ‘import’,
‘loader’, ‘name’, ‘package’, ‘spec’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’, ‘breakpoint’, ‘bytearray’,
‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’,
‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’,
‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’,
‘locals’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’,
‘quit’, ‘range’, ‘repr’, ‘reversed’, ‘round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’,
‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]
异常的继承关系:
BaseException 是所有异常的父类
断言测试
14.3 自定义异常
14.3.1 finally 关键字
finally:必须要执行的代码(释放资源、释放内存)
def dd(em): try: int(input()) print('hello') return 'A' except Exception as e: print('出现异常') return 'B' else: print('没有出现异常') finally: print('无论如何都会打印') return 'C' e=dd(input('>>>>>>>:')) print(e)
def demo(msg): try: int(input(msg)) print("hello world") return "A" except Exception as e: print("处理异常") return "B" finally: print("释放资源") return "C" res = demo(input(">>>>>:")) print(res)
注意:函数中,如果return后面存在finally,那么代码并不会直接返回,而是需要执行finally,再执行返回,所以finally会在return前执行
14.3.2 自定义异常
需要创建一个类,需要继承异常的父类(BaseException Exception)
#自定义异常 class myException(Exception): def __init__(self,m): #重写 Exception.__init__(self,m) def login(username,password): #raise 关键字 抛出异常 if username==None or username.strip()=='': raise myException('对不起,用户名不能为空') if password==None or password.strip()=='': raise myException('对不起,密码不能为空') if __name__ == '__main__': try: login(None,None) except Exception as e: print('异常是',e)
这篇关于学习Python 十二 (异常)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器
- 2024-11-16四种数据科学Web界面框架快速对比:Rio、Reflex、Streamlit和Plotly Dash
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门