第十章 异常处理

第十章 异常处理

10.1 异常的概念

异常:相对于正常而言,就是不正常的一种状态(情况),在程序的开发过程中会有错误或者BUG都是补充正常的情况(错误并不一定是异常,异常不等价与错误),异常指的是软件在正常的运行过程中,因为一些原因所引起(比如操作者使用不当)的程序错误,而导致软件崩溃的这种现象叫做异常

异常发生的后果:导致软件(程序)崩溃

10.2 为什么要处理异常

处理异常(容错):包容出现的不正常的错误,从而保证程序的正常执行

10.3 Python中异常的处理方案

处理异常的方式:

try - except语句块:异常的捕获处理

 num = int(input("请输入一个数字:"))
 result = num + 10
 print("{}+10={}".format(num,result))

代码目前出现了异常的这种情况,如果想要不影响代码的执行的化,需要异常的处理

在可能发生异常的代码前加上try语句块

try:

#有可能发生异常的代码(触发)

except:

#处理异常 ---- 捕获异常

 try:
     num = int(input("请输入一个数字:"))
     print("哈哈哈哈")
     result = num + 10
 except:
     print("发生异常了!!!!")
     
 print("{}+10={}".format(num,result))

 try:
     num = int(input("请输入一个数字:"))
     print("哈哈哈哈")
     result = num + 10
 except:
     print("发生异常了!!!!")
     print("开始处理异常了")
     num = int(input("必须输入一个数字:"))
     result = num + 10
 ​
 ​
 print("{}+10={}".format(num,result))
 print("结束了!!!!")

看不出来问题到底出现在哪儿 ------ 没有捕获异常的信息

 try:
     num = int(input("请输入一个数字:"))
     print("哈哈哈哈")
     result = num + 10
 except Exception as e:
     print("发生异常了!!!!",e)
     print("开始处理异常了")
     num = int(input("必须输入一个数字:"))
     result = num + 10
 ​
 ​
 print("{}+10={}".format(num,result))
 print("结束了!!!!")

常见异常:

import builtins

dir(builrins)

 >>> import builtins
 >>> dir(builtins)
 ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildPr
 ocessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsi
 s', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError
 ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'Lookup
 Error', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'Overflow
 Error', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', '
 RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True
 ', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarni
 ng', '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 的子类 是常见异常的父类)

10.4 finally关键字

finally:表示的是必须要执行的代码(释放资源 释放内存等)

 try:
     num = int(input("请输入一个数字:"))
 except Exception as e:
     print("发生异常了!!!!",e)
 finally:
     print("不管你的代码发不发生异常,这个部分我们都要执行")
 ​
 print("剩余的部分!!!")
 ​
 def demo(msg):
     try:
         int(input(msg))
         print("hello world")
         return "A"
     except Exception as e:
         print("处理异常",e)
         return "B"
     finally:
         print("释放资源")
         return "C"
     return "D"
 ​
 ​
 res = demo(input(">>>>>>>>>>>>>:"))
 print(res)

如果在控制台输入的是123,会打印什么????

 def demo(msg):
     try:
         int(msg)
         print("hello world")
         return "A"
     except Exception as e:
         print("处理异常",e)
         return "B"
     finally:
         print("释放资源")
         return "C"
     return "D"
 ​
 ​
 res = demo(input(">>>>>>>>>>>>>:"))
 print(res)

函数中,如果return的后面存在finally,那么代码不会被直接进行返回,而是先执行完finally,再执行返回(return)

10.5 自定义异常

自定义异常------- 定义一个类,这个类继承Exception 或者BaseException,建议继承Exception

class MyException(Exception):
    def __init__(self,msg):
        Exception.__init__(self,msg)
class MyException(Exception):
    def __init__(self,msg):
        Exception.__init__(self,msg)

def login(username,password):
    if username == None or username.strip() == "":
        # print("用户名不能为空")
        #抛出异常  ----- 使用rasie关键字(抛出异常---- 自定义的异常,系统自带的异常)
        raise MyException("对不起,用户名不能为空")
    if password == None or password.strip() == "":
        # print("密码不能为空")
        # 抛出异常  ----- 使用rasie关键字(抛出异常---- 自定义的异常,系统自带的异常)
        raise MyException("对不起,密码不能为空")

if __name__ == '__main__':
    # login(None,None)
    #捕获异常
    try:
        login(None,None)
    except Exception as e:
        print("捕获到的异常是--------->",e)

rasie关键字抛出异常

注意:人为的抛出异常的作用:提示错误,向上传递错误的信息。

  • 19
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

璀云霄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值