1.异常
1.1.异常概念
相较于正常而言不正常的现象叫做哟异常,在程序开发过程中遇到的错误或bug都是补充正常情况(错误并非异常,异常并非等价于错误,异常指的是软件在运行的过程中,因为一些原因【如:使用者使用不当】引起的程序错误,导致软件崩溃的现象,叫做异常)
异常发生的后果:导致程序的崩溃
1.2.相关知识点
python篇 面向对象
python篇 io流运用
python篇 流程控制语句
2.异常处理
处理异常(容错):包容出现不正常的错误,保证程序的正常运行,
处理异常方式:try-except()语句块-----异常捕获
num = int(input("请输入一个数字:"))
result = num + 10
print("{} + 10 = {}".format(num,result))
比如我非要输入字符
请输入一个数字:zhangsan
Traceback (most recent call last):
File "D:\python\pyc\学习\异常.py", line 1, in <module>
num = int(input("请输入一个数字:"))
ValueError: invalid literal for int() with base 10: 'zhangsan'
Process finished with exit code 1
代码出现异常:并不影响后面代码的执行,需要继续执行下面的代码
3.语法格式
try:
//有可能发生异常的代码
except:
//处理异常
try:
num = int(input("请输入一个数字:"))
print("哈哈哈哈")
print("哈哈哈哈")
result = num + 10
except:
print("你疯了!居然不输入数字!")
print("结束")
# print("{} + 10 = {}".format(num,result))
E:\py\python.exe D:/python/pyc/学习/异常.py
请输入一个数字:张三
你疯了!居然不输入数字!
结束
Process finished with exit code 0
改
try:
num = int(input("请输入一个数字:"))
print("哈哈哈哈")
print("哈哈哈哈")
result = num + 10
except:
print("你疯了!居然不输入数字!")
print("开始处理异常")
num = int(input("必须输入的是数字:"))
result = num + 10
print("结束")
print("{} + 10 = {}".format(num,result))
捕获异常 Exception as e
try:
num = int(input("请输入一个数字:"))
print("哈哈哈哈")
print("哈哈哈哈")
result = num + 10
except Exception as e:
print("发生了异常",e)
print("你疯了!居然不输入数字!")
print("开始处理异常")
num = int(input("必须输入的是数字:"))
result = num + 10
print("结束")
print("{} + 10 = {}".format(num,result))
ValueError
try:
num = int(input("请输入一个数字:"))
print("哈哈哈哈")
print("哈哈哈哈")
result = num + 10
except ValueError as b:
print("发生了异常",b)
print("你疯了!居然不输入数字!")
print("开始处理异常")
num = int(input("必须输入的是数字:"))
result = num + 10
print("结束")
print("{} + 10 = {}".format(num,result))
常见异常
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()所有异常父类
Exception() 常见异常父类,BaseException子类
4.finally关键字
表示必须执行的代码放到finally中
finally:该关键字表示,必须(必要)执行的代码(释放资源)
try:
num = int(input("请输入一个数字:"))
print("哈哈哈哈")
print("哈哈哈哈")
result = num + 10
except ValueError as b:
print("发生了异常",b)
print("你疯了!居然不输入数字!")
print("开始处理异常")
else:
print("没有发生异常")
finally:
print("不管如何都要执行")
再来
def demo(msg):
try:
input(msg)
print("hello world")
return "A"
except Exception as e:
print("处理了异常")
return "B"
finally:
print("释放资源")
return "C"
return "D"
res = demo(input(">>>>>>:"))
print(res)
123>? 123
hello world
释放资源
C
如果return后存在finally,代码不会直接返回,而是需要去执行finally代码块,再执行返回
5.自定义异常
自定义异常:首先创建一个类,之后继承Ecception或者BaseException,建议继承Exception
raise弹出异常
class MyException(Exception):
def __init__(self,msg):
Exception.__init__(self,msg)
def login(username,password):
if username == "" or username == None:
#抛出异常 ---- 使用 raise 关键字(自定义的异常进行抛出)
raise MyException("用户名不能为空!")
if username == "" or username == None:
#抛出异常 ---- 使用 raise 关键字(自定义的异常进行抛出)
raise MyException("密码不能为空!")
if __name__ == '__main__':
# login(None,None)
# 异常捕获
try:
login(None, None)
except Exception as e:
print("捕获到的异常,信息是--->",e)