异常处理(try...except...)

    技术2023-12-28  98

    1、异常基础

    在编程过程中为了增加友好性,在程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面,通俗来说就是不让用户看见大黄页!!!相关代码如下:

    try: pass except (IndexError,FileNotFoundError,KeyError) as e: #多个错误可以用元组形式 print(e) #e是错误日志 except Exception as e: #可以捕获任意异常,抓取未知错误,放在最后,不建议一开始用。 print('未知错误',e) else: print('一切正常') #没有错误时执行 finally: print('不管有没有错都执行') #不管有没有错,一定会执行

    注:finally可以用于在发生异常时执行清理工作。非常适合用于确保文件或网络套接字等得以关闭。

    2.常用异常

    python中的异常种类非常多,每个异常专门用于处理某一项异常!!!

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常;基本上是无法打开文件(python2) ImportError 无法引入模块或包;基本上是路径问题或名称错误 IndentationError 语法错误(的子类) ;代码没有正确对齐 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] KeyError 试图访问字典里不存在的键 KeyboardInterrupt Ctrl+C被按下 NameError 使用一个还未被赋予对象的变量 SyntaxError Python代码非法,代码不能编译 TypeError 传入对象类型与要求的不符合 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 导致你以为正在访问它 ValueError 传入一个调用者不期望的值,即使值的类型是正确的 FileNotFoundError 没有找到指定打开的文件
    示例1:
    s1 = 'hello' try: int(s1) except ValueError as e: print('error',e)

    输出:

    error invalid literal for int() with base 10: 'hello'
    示例2:
    dic = {'k1':'v1'} try: dic['k20'] except KeyError as e: print('KeyError',e)

    输出:

    KeyError 'k20'
    示例3
    dic = ["wupeiqi", 'alex'] try: dic[10] except IndexError as e: print('IndexError:',e)

    输出:

    IndexError: list index out of range

    3.自定义异常

    class AlexException(Exception): #继承 def __init__(self, msg): self.message = msg try: raise AlexException('我的异常') #主动出发异常 except AlexException as e: print(e)

    输出:

    我的异常

    4.一个非常巧妙的程序

    while True: try: x = int(input('enter the first number:').strip()) y = int(input('enter the second number:').strip()) value = x / y print(value) except Exception as e: print('Invaild input:',e) print('please try again') else: break

    仅当没有引发异常时,才会跳出循环,只要出现异常,程序会要求用户提供新的输入。

    enter the first number:10 enter the second number:0 Invaild input: division by zero please try again enter the first number:fa Invaild input: invalid literal for int() with base 10: 'fa' please try again enter the first number:10 enter the second number:2 5.0
    Processed: 0.030, SQL: 9