笔记-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. 移植MAVLINK到STM32详细教程之三

    在前面教程的基础上继续移植优化,之前的没有加缓冲区,没有接收函数功能,这里进行统一的讲解                            作者:恒久力行  qq:624668529 缓冲区对于接 ...

  2. Servlet高级部分Filter(过滤器)

    一:Filter称之为"过滤器",用在Servlet外,对request和response进行修改.它是AOP(面向切面编程思想的一种体现),Filter中有一个FilterCha ...

  3. Flask蓝图的增删改查

    怎样用flask蓝图来实现增删改查呢?请看下面的内容 这是我们的目录结构 从图中可以看出每一个功能都有一个各自的文件夹 首先我们要自己先来创建一个数据,在Flask_data.py中写入如下内容: S ...

  4. 构建第一个Spring Boot2.0应用之application.properties和application.yml(八)

    本节学习在项目中配置文件配置的方式,一种是通过applicaiton.properties,一种是通过application.yml方式. 一.环境: IDE:IntelliJ IDEA 2017.1 ...

  5. C# Dictionary的遍历

    foreach (KeyValuePair<string, string> kvp in dic) { Console.WriteLine("key:{0},value:{1}& ...

  6. python decorator 用法

    https://www.zhihu.com/question/31265857 http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html ...

  7. Linux命令技巧:如何在Linux下重命名多个文件

    我知道我可以用mv命令重命名文件.但是当我想重命名很多文件怎么办?如果为每个文件都这么做将会是很乏味的.有没有办法一次性重命名多个文件? 在Linux中,当你想要改变一个文件名,使用mv命令就好了.然 ...

  8. Q9400为何难以100%全速运行

    采用基于正域的约简. 数据:Ticdata2000 记录数:5822 条件属性:85 结果: 1. Core i7 3632QM 4四核八线程 2.2G 动态加速3.2G 0.516s 2. Core ...

  9. bzoj4622 [NOI 2003] 智破连环阵

    Description B国在耗资百亿元之后终于研究出了新式武器——连环阵(Zenith Protected Linked Hybrid Zone).传说中,连环阵是一种永不停滞的自发性智能武器.但经 ...

  10. Wired Memory

    https://developer.apple.com/library/content/documentation/Performance/Conceptual/ManagingMemory/Arti ...