• 大爽Python入门教程 75 异常处理 try ... except Exception


    大爽Python入门公开课教案 点击查看教程总目录

    1 什么是异常Exception

    简单来讲,错误Error就是异常Exception

    具体的,我们先来看几个错误。

    >>> 2:3
    SyntaxError: illegal target for annotation
    >>> 2 + ""
    Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
        2 + ""
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    >>> int("")
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        int("")
    ValueError: invalid literal for int() with base 10: ''
    

    这里面的SyntaxErrorTypeErrorValueError是报错。
    指出了错误的具体类型(大概情况)

    所有这些Error类,其根本类(始祖)是Exception
    Exception是其父类或者其父类的父类,或者其父类的父类的父类...)

    Error类的具体继承关系,可以看官方文档:
    exception-hierarchy

    当然,很多时候并不需要分这么清楚。
    平时描述,基本报错和异常是一个意思。

    2 处理异常

    介绍

    一般来讲,有错误,就会导致程序直接终止。

    但有时候,我们希望报错不会影响程序运行。
    或者需要判断错误是否执行。
    那么就需要使用try...except语法来处理错误。

    举个例子,我们之前接受用户输入时,会用isdigit来判断输入是否能转换成数字。

    现在我们有了新方法,如下

    try:
        i = input()
        i = int(i)
        print(i)
    except Exception as e:
        print(e)
    

    运行时
    如果输入为数字,比如12, 则输出对应数字12

    如果输入不是数字,比如dsafd
    则输出invalid literal for int() with base 10: 'dsafd'
    注意:这个时候程序不是报错终止,而是把错误打印了出来。

    也就是用户输入数字的时候,
    try管辖的代码的会正常运行,except管辖的不会运行。

    输入不是数字导致程序无法运行的时候(int(i)报错的时候)
    try管辖的代码的会停止运行,
    except管辖的代码会运行。

    语法

    try...except...的基本格式为

    try:
        # statement1
    except:
        # statement2
    

    该语法效果为,
    先尝试执行try管辖的statement1代码,如果遇到异常,则停止。
    去执行except管辖的statement2代码。

    从中文上讲,except可以理解为捕获(异常)的意思。

    有时候我们需要知道具体发生了什么异常,将异常输出或者做其他使用的时候,
    则会使用except Exception as e,如下

    try:
        # statement1
    except Exception as e:
        # statement2
    

    此时except Exception as e这一句中的as e
    会把捕获到的异常赋值给e,然后可以在statement2中使用。
    (此时e是局部变量,只能在except管辖的statement2中使用)

    as e中的e只是一个变量名,并不是固定语法,可以起自己需要的名字。

    示例分析

    我们知道,数字和字符串无法直接加减。会报错
    比如这个代码

    x = "12" + 12
    

    直接执行会报错如下

    Traceback (most recent call last):
      File "H:\github projects\big-shuang-python-introductory-course\codes\course7\demo502.py", line 1, in <module>
        x = "12" + 12
    TypeError: can only concatenate str (not "int") to str
    

    这里我们放在try...except语法中,看其效果

    try:
        print("start...")
        x = "12" + 12
        print("end...")
    except Exception as ee:
        print("error: ",ee)
    

    执行时输出如下

    start...
    error:  can only concatenate str (not "int") to str
    

    这里分析以下其详细步骤

    1. print("start...")成功执行
    2. x = "12" + 12报错,停止继续执行try管辖的代码(print("end...")没有执行)
    3. 捕获到异常,赋值给ee
    4. 执行print("error: ",ee)

    3 抛出异常

    基础语法

    上面介绍了捕获异常,下面来了解下如何抛出异常。
    这个常和try...expect配合使用。
    一抛一接。

    抛出异常的语法非常简单:

    raise Exception()
    

    raise可以理解为抛出的意思。

    其运行效果如下

    Traceback (most recent call last):
      File "H:\github projects\big-shuang-python-introductory-course\codes\course7\demo503.py", line 1, in <module>
        raise Exception()
    Exception
    

    加信息

    我们也可以在抛出的异常中加入一些说明信息
    比如

    raise Exception("This is a base exception")
    

    其运行效果如下

    Traceback (most recent call last):
      File "H:\github projects\big-shuang-python-introductory-course\codes\course7\demo503.py", line 1, in <module>
        raise Exception("This is a base exception")
    Exception: This is a base exception
    

    自定义

    不仅如此,我们还可以自定义异常类。
    如下

    class SimpleError(Exception):
        pass
    
    raise SimpleError("Oh")
    

    其运行效果如下

    Traceback (most recent call last):
      File "H:\github projects\big-shuang-python-introductory-course\codes\course7\demo503.py", line 5, in <module>
        raise SimpleError("Oh")
    __main__.SimpleError: Oh
    

    4 拓展进阶

    用的很少,简单了解就行。(我基本没怎么用过这些)

    except拓展

    接下来详细介绍下except语法
    except Exception这一句,会捕获所有异常。
    其实except也可以捕获特定异常。
    比如要捕获TypeError
    可以写为except TypeError

    也就是except后面跟的是要捕获的异常类。
    一个try语句可以接多个except语句,就像一个if后面可以接多个elif一样。

    try:
        pass # statement1
    except TypeError as e1:
        pass # statement 2
    except ValueError as e2:
        pass # statement 3
    except Exception as e2:
        pass # statement 3
    

    finally子句

    try:
        pass # statement1
    except Exception:
        pass # statement2
    finally:
        pass # statement3
    

    不管try管辖的代码是否引发错误,
    finally管辖的代码永远会被执行。

  • 相关阅读:
    Maven pom.xml中的元素modules、parent、properties以及import
    基于SpringBoot搭建应用开发框架(一) —— 基础架构
    Spring Boot项目使用Eclipse进行断点调试Debug
    eclipse 运行springboot项目
    如何在eclipse中使用mvn clean install
    https://www.cnblogs.com/zy-jiayou/p/7661415.html
    SpringBoot系列三:SpringBoot基本概念(统一父 pom 管理、SpringBoot 代码测试、启动注解分析、配置访问路径、使用内置对象、项目打包发布)
    WebJars are client-side web libraries (e.g. jQuery & Bootstrap) packaged into JAR (Java Archive) files
    在EF中使用Expression自动生成p=>new Entity(){X="",Y="",..}格式的Lambda表达式灵活实现按需更新
    EF跨库查询,DataBaseFirst下的解决方案
  • 原文地址:https://www.cnblogs.com/BigShuang/p/15757810.html
Copyright © 2020-2023  润新知