异常处理
1.什么是异常?
异常指的是软件在运行的过程中,因为一些原因(如:使用者操作不当等),引起的程序错误
2.常见的异常有哪些?
>>> 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']
3.异常的继承关系
BaseException:所有异常的超类
Exception:是BaseException的子类,包括所有的常见的异常
4.Python是如何处理异常:try: … except:…
1.一般异常处理格式:
try:
#触发异常的代码
expect Exception as e:
#异常处理
else:
#try无异常时,则会执行else中的代码
finally:
#不管出不出现异常,都要执行(释放资源,释放链接,释放内存等)
2. 多个异常处理方法一(推荐):
try:
#将可能触发异常的代码
except XXX as e:
print("处理异常,异常信息:",e)
except Exception as e:
print("使用多态将其他异常一网打尽")
else:
print("try无异常时,则会执行else中的代码")
多个异常处理方法二(不推荐):
try:
#触发异常的代码
except (keyboaredInteerupt,ValueError,KeyError) as e:
#处理异常的代码
注:在函数中,如果return后面存在finally,那么代码并不会直接返回所要返回的值,而是先执行finally中的代码,之后才执行返回值
举例:
def demo(msg):
try:
int(msg)
return "a"
except Exception as e:
print("处理异常")
return "b"
finally:
print("释放资源")
res=demo(input("请输入"))
print(res)
结果如下:
请输入:123
释放资源
a
5.自定义异常的使用(raise关键字):首先需要定义一个类,之后让这个类继承Exception/BaseException,当然建议使用Exception
作用:提示错误,向上层传递信息
举例:
class MyException(Exception): #自定义一个异常类,继承Exception异常类,使之后的用Exception能够抓取异常信息
def __init__(self, msg):
Exception.__init__(self, msg)
def login(username, password):
if username is None or username.strip() == "":
# 抛出异常,使用raise关键字抛出异常
# 认为的抛出异常,1、这儿出了错, 2、向调用者传递信息
raise MyException("对不起,用户名称不能为空") #使用该异常类将自定义的异常信息传递到该类的初始化函数的参数
if password is None or password.strip() == "":
raise Exception("对不起,用户密码不能为空")
print("登录成功")
if __name__ == '__main__':
try:
login(input(">>"), input(">>"))
except Exception as e: #抓取自定义的异常信息
print("抓捕到异常,信息是--->", e)
结果如下:
>>ss
>>
抓捕到异常,信息是---> 对不起,用户密码不能为空