学习Python 十二 (异常)

学习Python 十二 (异常),第1张

概述14.异常14.1什么是异常异常:正常的情况,运行程序的过程中出现问题,BUG(错误不一定是异常)14.2处理异常try代码块try: #放的是有可能造成异常的代码except: #处理异常如:try:num=int(input('输入一个数:'))result=num+11exceptExceptionase:pri 14.异常14.1 什么是异常

异常:正常的情况,运行程序的过程中出现问题,BUG(错误不一定是异常)

14.2 处理异常

try代码块

try:	#放的是有可能造成异常的代码except:	#处理异常

如:

try:    num = int(input('输入一个数:'))    result= num+11except Exception as e:    print('出现异常')    print('在这里处理异常',e)    num=int(input('重新输入一个数:'))    result=num+11print(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 十二 (异常)全部内容,希望文章能够帮你解决学习Python 十二 (异常)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1187145.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存