美文网首页
2019实战第二期-异常读书打卡

2019实战第二期-异常读书打卡

作者: tipire | 来源:发表于2019-03-23 22:19 被阅读0次

-----学习《Python基础教程第3版》读书笔记-----

2019实战第二期-异常读书打卡

异常是什么

使用异常对象表示异常状态,并在遇到错误时引发异常。异常对象未被处理,程序将终止并显示一条错误信息(traceback)

让事情沿你指定的轨道出错

出现问题时,将自动引发异常。

raise语句
raise Exception
raise Exception('hyperdrive overload')
1553348797317.png

虽然内置异常涉及的范围很广,能够满足很多需求,但有时你可能想自己创建异常类。

那么如何创建异常类呢?就像创建其他类一样,但务必直接或间接地继承 Exception (这意味着从任何内置异常类派生都可以)。因此,自定义异常类的代码类似于下面这样:
class SomeCustomException(Exception): pass
捕获异常

异常比较有趣的地方是可对其进行处理,通常称之为捕获异常。为此,可使用try / except 语句。

try:
    x = int(input('Enter the first number: '))
    y = int(input('Enter the second number: '))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")
异常和函数
不提供参数
class MuffledCalculator:
    muffled = False
    def calc(self, expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print('Division by zero is illegal')
            else:
                raise
多个except
try:
    x = int(input('Enter the first number: '))
    y = int(input('Enter the second number: '))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")
except TypeError:
    print("That wasn't a number, was it?")
捕获多个异常
try:
    x = int(input('Enter the first number: '))
    y = int(input('Enter the second number: '))
    print(x / y)
except (ZeroDivisionError, TypeError, NameError):
    print('Your numbers were bogus ...')
捕获对象
try:
    x = int(input('Enter the first number: '))
    y = int(input('Enter the second number: '))
    print(x / y)
except (ZeroDivisionError, TypeError) as e:
    print(e)
捕获所有异常
try:
    x = int(input('Enter the first number: '))
    y = int(input('Enter the second number: '))
    print(x / y)
except:
    print('Something wrong happened ...')
万事大吉
while True:
    try:
        x = int(input('Enter the first number: '))
        y = int(input('Enter the second number: '))
        value = x / y
        print('x / y is', value)
    except Exception as e:
        print('Invalid input:', e)
        print('Please try again')
    else:
        break
加finally
try:
    1 / 0
except NameError:
    print("Unknown variable")
else:
    print("That went well!")
finally:
    print("Cleaning up.")

异常和函数有着天然的联系。如果不处理函数中引发的异常,它将向上传播到调用函数的地方。如果在那里也未得到处理,异常将继续传播,直至到达主程序(全局作用域)。如果主程序中也没有异常处理程序,程序将终止并显示栈跟踪消息。

>>> def faulty():
... raise Exception('Something is wrong')
...
>>> def ignore_exception():
... faulty()
...
>>> def handle_exception():
... try:
...  faulty()
...  except:
...  print('Exception handled')
...
>>> ignore_exception()
Traceback (most recent call last):
File '<stdin>', line 1, in ?
File '<stdin>', line 2, in ignore_exception
File '<stdin>', line 2, in faulty
Exception: Something is wrong
>>> handle_exception()
Exception handled
异常之禅
def describe_person(person):
    print('Description of', person['name'])
    print('Age:', person['age'])
    try:
        print('Occupation:', person['occupation'])
    except KeyError: pass
不那么异常的情况

只是发出警告,指出情况偏离了正轨

>>> from warnings import warn
>>> warn("I've got a bad feeling about this.")
__main__:1: UserWarning: I've got a bad feeling about this.

>>> filterwarnings("error")
>>> warn("This function is really old...", DeprecationWarning)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
DeprecationWarning: This function is really old...
>>> filterwarnings("ignore", category=DeprecationWarning)
>>> warn("Another deprecation warning.", DeprecationWarning)
>>> warn("Something else.")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UserWarning: Something else.

相关文章

  • 2019实战第二期-异常读书打卡

    -----学习《Python基础教程第3版》读书笔记----- 2019实战第二期-异常读书打卡 异常是什么 使用...

  • 2019实战第二期-异常实战打卡

    2019实战第二期-异常实战打卡 题目:编写一个迷你的计算器,支持两个数加,减,乘,除要求提示用户输入2个数字和一...

  • 2019实战第二期-时间读书打卡

    2019实战第二期-时间读书打卡 --读《Python编程快速上手—让繁琐工作自动化》 Python里面的并发分2...

  • 2019实战第二期-文件格式读书打卡

    2019实战第二期-文件格式读书打卡 读《Python编程快速上手—让繁琐工作自动化 PDF中文高清晰完整版》笔记...

  • 20180708(日)

    做智慧父母,育卓越孩子。祥和父母学院21天打卡实战营第二期《高效沟通》打卡D4天 悦实战,悦成长 今天早上雷阵雨,...

  • 20180706(五)

    做智慧父母,育卓越孩子。祥和父母学院21天打卡实战营第二期《高效沟通》打卡D2天 悦实战,悦成长 冯老师高效沟通的...

  • 20180705(四)

    做智慧父母,育卓越孩子。祥和父母学院21天打卡实战营第二期《高效沟通》打卡D1天 悦实战,悦成长 冯老师高效沟通的...

  • 2019实战第二期-文件读书打卡

    -----学习《Python基础教程第3版》读书笔记----- 打开文件 ​ 要打开文件,使用open函数,不...

  • 2019实战第二期-函数读书打卡

    抽象之函数 函数可以尽量避免重复的代码,简化代码。函数式结构化编程的核心。 函数执行特定的操作并返回一个值 运行这...

  • 2019实战第二期-控制读书打卡

    -----学习《Python基础教程第3版》读书笔记----- 条件 循环 while for 跳出循环

网友评论

      本文标题:2019实战第二期-异常读书打卡

      本文链接:https://www.haomeiwen.com/subject/devevqtx.html