zoukankan      html  css  js  c++  java
  • 【Python基础】之异常

    一、常见异常

    try:
        open('abc.txt','r')
    except FileNotFoundError:
        print('异常啦!')
    
    输出结果:
    ======= 异常啦!

    我们通过 open()方法以读“r”的方式打开一个 abc.txt 的文件。然后 Python 抛出一个FileNotFoundError 类型的异常,它告诉我们:No such file or directory:“abc.txt”(没有abc.txt 这样的文件或目录)。当然找不到,因为我们根本就没创建这个文件。

    既然知道执行 open()一个不存在的文件时会抛 FileNotFoundError 异常,那么我们就可以通过 Python 所提供的 try...except...语句来接收并处理这个异常。

    二、基类BaseException

    try:
        open(aa)
    except BaseException:
        print('异常啦!')
    
    
    输出结果:
    =======
    异常啦!

    三、msg变量接收异常信息

    try:
        open('abc.txt','r')
        print(aa)
    except BaseException as msg:
        print(msg)
    
    输出结果:
    =======
    [Errno 2] No such file or directory: 'abc.txt'

    Python中常见的异常如下表:

    四、try...except...else的使用

    try:
        a = '测试:'
        print(a)
    except Exception as msg:
        print(msg)
    else:
        print('没有异常!')
    
    
    输出结果:
    =======
    测试:
    没有异常!

    五、try...except...finally的使用

    try:
        print(a)
    except Exception as msg:
        print(msg)
    finally:
        print('我永远被执行!')
    
    输出结果:
    ======
    name 'a' is not defined
    我永远被执行!

    六、抛出异常raise

    from random import randint
    
    #1~9随机数选
    number = randint(1,9)
    
    if number % 2 == 0:
        raise NameError('%d is even' %number)
    else:
        raise NameError('%d is odd',%number)
    
    输出结果:
    ======
    Traceback (most recent call last):
      File "F:Pytestabnormal.py", line 30, in <module>
        raise NameError("%d is odd" %number)
    NameError: 7 is odd
  • 相关阅读:
    Kotlin协程第一个示例剖析及Kotlin线程使用技巧
    大数据JavaWeb之java基础巩固----Junit&反射&注解
    Kotlin协程重要概念详解【纯理论】
    Kotlin反射在属性上的应用实战
    Kotlin反射操纵构造方法与伴生对象
    个人任务day4
    典型用户和用户场景
    个人任务Day3
    个人任务2
    个人任务1
  • 原文地址:https://www.cnblogs.com/Owen-ET/p/7097008.html
Copyright © 2011-2022 走看看