笔记-python-tutorial-8.errors and exceptions

1.      errors and exceptions

1.1.    syntax errors

>>> while True print('Hello world')

File "<stdin>", line 1

while True print('Hello world')

^

SyntaxError: invalid syntax

1.2.    异常处理

>>> while True:

...     try:

...         x = int(input("Please enter a number: "))

...         break

...     except ValueError:

...         print("Oops!  That was no valid number.  Try again...")

...

try语句工作原理:

  1. 首先,执行try和except之间的语句;
  2. 如果没有异常出现,except语句后的内容不执行,try语句执行结束;
  3. 如果在执行第一步时出现异常,剩余语句将跳过;如果抛出的异常类型与except后的关键字匹配,except部分语句执行;
  4. 如果出现异常但不匹配except给出的关键字类型,except后的语句将跳过,异常被抛给更外围的try语句,如果没有任何try语句捕获该异常,则输出缺省的出错信息。

一个try可以有多个except部分。

... except (RuntimeError, TypeError, NameError):

...     pass

更好的写法,最后一个except语句最好不带异常名,这样它可以处理所有的异常信息。

import sys

try:

f = open('myfile.txt')

s = f.readline()

i = int(s.strip())

except OSError as err:

print("OS error: {0}".format(err))

except ValueError:

print("Could not convert data to an integer.")

except:

print("Unexpected error:", sys.exc_info()[0])

raise

else语句,如果没有异常则执行此语句。

for arg in sys.argv[1:]:

try:

f = open(arg, 'r')

except OSError:

print('cannot open', arg)

else:

print(arg, 'has', len(f.readlines()), 'lines')

f.close()

try-finally语句,无论是否有异常,都将执行该语句。

try:

<语句>

finally:

<语句>    #退出try时总会执行

raise

except语句可以在异常名后指定一个变量,这个变量与一个异常实例绑定,参数存于instance.args

>>> try:

...     raise Exception('spam', 'eggs')

... except Exception as inst:

...     print(type(inst))    # the exception instance

...     print(inst.args)     # arguments stored in .args

...     print(inst)          # __str__ allows args to be printed directly,

...                          # but may be overridden in exception subclasses

...     x, y = inst.args     # unpack args

...     print('x =', x)

...     print('y =', y)

...

<class 'Exception'>

('spam', 'eggs')

('spam', 'eggs')

x = spam

y = eggs

1.3.    raising exceptions

raise语句可以触发一个异常。

raise [Exception [, args [, traceback]]]

>>> raise NameError('HiThere')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: HiThere

1.4.    自定义异常

通过创建新的异常类,用户可以定义自己的异常类。一般情况下从Exception类直接或间接派生类。

异常类和其它类在本质上没什么不同,但一般只用异常类提供异常信息。

1.5.    异常清理

try…finally语句可以实现异常清理功能。

>>> def divide(x, y):

...     try:

...         result = x / y

...     except ZeroDivisionError:

...         print("division by zero!")

...     else:

...         print("result is", result)

...     finally:

...         print("executing finally clause")

...

>>> divide(2, 1)

result is 2.0

executing finally clause

>>> divide(2, 0)

division by zero!

executing finally clause

>>> divide("2", "1")

executing finally clause

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<stdin>", line 3, in divide

TypeError: unsupported operand type(s) for /: 'str' and 'str'

1.6.    预定义清理操作

部分对象定义了标准清理操作,当该对象不在使用时执行,不论对该对象的操作成功与否。

典型的是文件打开和关闭,在这种情况下通常使用with语句。

with open("myfile.txt") as f:

for line in f:

print(line, end="")

笔记-python-tutorial-8.errors and exceptions的更多相关文章

  1. 《The Python Tutorial》——Errors and Exceptions 阅读笔记

    Errors and Exceptions 官方文档:https://docs.python.org/3.5/tutorial/errors.html python中所有的异常都继承自BaseExce ...

  2. [译]The Python Tutorial#8. Errors and Exceptions

    [译]The Python Tutorial#Errors and Exceptions 到现在为止都没有过多介绍错误信息,但是已经在一些示例中使用过错误信息.Python至少有两种类型的错误:语法错 ...

  3. Python Tutorial 学习(八)--Errors and Exceptions

    Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...

  4. Python Tutorial笔记

    Python Tutorial笔记 Python入门指南 中文版及官方英文链接: Python入门指南 (3.5.2) http://www.pythondoc.com/pythontutorial3 ...

  5. 笔记-python lib-pymongo

    笔记-python lib-pymongo 1.      开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...

  6. [译]The Python Tutorial#4. More Control Flow Tools

    [译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...

  7. [Notes] Learn Python2.7 From Python Tutorial

    I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...

  8. Python Tutorial 学习(六)--Modules

    6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...

  9. Handling Errors and Exceptions

    http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...

随机推荐

  1. C# 的两种debug 方法

    第一种:需要把调试方法改成debug代码用 #if DEBUG 包裹 using System; using System.Collections.Generic; using System.Text ...

  2. 《Head First 设计模式》之适配器模式与外观模式

    适配器模式(Adapter) 适配器(adapter-pattern):将一个类的接口,转换成客户期望的另一个接口.适配器让原来接口不兼容的类可以合作无间.两种形式: 对象适配器(组合) 类适配器(多 ...

  3. 零基础逆向工程24_C++_01_类_this指针_继承本质_多层继承

    1 类内的成员函数和普通函数的对比 1.1 主要是从参数传递.压栈顺序.堆栈平衡来总结. 1.参数传递:成员函数多传一个this指针 2.压栈顺序:成员函数会将this指针压栈,在函数调用取出 3.堆 ...

  4. linux打开文件数测试

    /proc/sys/kernel/threads-max 系统最大线程数量 /proc/sys/vm/max_map_count 限制一个进程可以拥有的VMA(虚拟内存区域)的数量 /proc/sys ...

  5. Python自学之路——自定义简单装饰器

    看了微信公众号推送的一道面试题,发现了闭包的问题,学习时间短,从来没有遇到过这种问题,研究一下. Python函数作用域 global:全局作用域 local:函数内部作用域 enclosing:函数 ...

  6. 在一个css文件中引入其他css文件

    @import "./main.css";@import "./color-dark.css";@import "./reset.css";

  7. System.FormatException: GUID 应包含带 4 个短划线的 32 位数(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)。解决办法

    查一下数据库的UID数据是否格式正确,如: 错误格式1: {E056BB36-D824-4106-A9C3-D8D8B9ADC1C 错误格式2: E056BB36-D824-4106-A9C3-D8D ...

  8. PL/SQL的安装

    一.下载PLSQLDeveloper 网址:https://www.allroundautomations.com/bodyplsqldevreg.html 还需要一个激活码 二.PL/SQL的安装 ...

  9. Mac 系统 + Chrome浏览器 网页前端出现中文文字反转或顺序错乱

    问题背景 React开发的系统,收到一个BUG反馈,*"号个人统计"文字不正确,应为"个人号统计"*. 收到BUG后,打开浏览器查验是什么情况,难道犯了最基本的 ...

  10. 关于小程序 input 组件内容显示不全(显示的长度不满 input 宽度)问题

    问题:小程序的input组件经常用到,但在使用input组件的时候会出现一种现象:明明设置了input的宽度,但是输入的内容显示的长度范围却怎么都不到一整个input组件的宽度,而且后面没显示的地方无 ...