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)