我们在编码的过程中,难免会遇到一些错误和异常, 这时候程序会异常退出,并且会抛出错误信息:

比如:

print(1/0)

'''
输出:
Traceback (most recent call last):
File "D:/PythonStudy/errors.py", line 3, in <module>
print(1/0)
ZeroDivisionError: division by zero
'''

我们尝试让1 去除0,结果系统报错了异常  ‘ZeroDivisionError: division by zero’, 表示不能被零除。

Python内置许多异常,当出现这些问题时,会提示我们并中断运行,python3.7中主要有以下的异常:

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning

有关内置异常的详细描述可以参考python的相关文档,链接如下: https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions

Python提供了一套方式,用来捕获和处理错误和异常:

使用try....except...finally来对可能存在的错误进行处理:

#-*- coding:utf-8 -*-

try:
print(1/0)
except ZeroDivisionError:
print('Can not division 0, happen ZeroDivisionError')
finally:
print('Go to next step') '''
输出:
Can not division 0, happen ZeroDivisionError
Go to next step
'''

通过上面的例子,我们可以看到,代码首先执行try里的code,如果遇到了指定的错误,那么就执行except中的代码, 处理完毕后执行finally中的代码。

在每个代码块中,支持各种判断和迭代,其工作的流程结构如下:

除了系统内置的错误,我们也可以在代码中主动抛出一些错误:

#-*- coding:utf-8 -*-
name = 'ralf'
if name != 'rachel':
raise Exception('The name is not ralf') '''
输出:
Traceback (most recent call last):
File "D:/PythonStudy/errors.py", line 4, in <module>
raise Exception('The name is not ralf')
Exception: The name is not ralf
'''

我们也可以通过继承Exception base class,自定我们自己的错误类型:

#-*- coding:utf-8 -*-
class NameError(Exception):
def __init__(self, level, message):
self.level = level
self.message = message
try:
name = 'ralf'
if name != 'rachel':
raise NameError('Error', 'Name is not right')
except NameError as e:
print(e.level)
print(e.message)
'''
输出:
Error
Name is not right
'''

Python 学习笔记18 异常处理的更多相关文章

  1. Python学习笔记之异常处理

    1.概念 Python 使用异常对象来表示异常状态,并在遇到错误时引发异常.异常对象未被捕获时,程序将终止并显示一条错误信息 >>> 1/0 # Traceback (most re ...

  2. 【Python学习笔记】异常处理try-except

    Python异常处理 我们一般使用try-except语句来进行异常处理. 使用except Exception as err可以统一捕捉所有异常,而也可以分开处理单个异常. # 分开捕捉单个异常 t ...

  3. python学习笔记(异常处理)

    上次提到正则表达式 当未匹配到数据返回值 None 再使用 match.group 会出现异常 AttributeError 为了避免异常我改成“ match != None” 这次加入异常处理 #! ...

  4. Python学习笔记9——异常处理

    处理异常 如果执行到程序中某处抛出了异常,程序就会被终止并退出.你可能会问,那有没有什么办法可以不终止程序,让其照样运行下去呢?答案当然是肯定的,这也就是我们所说的异常处理,通常使用 try 和 ex ...

  5. python学习笔记18(UliPad 初体验)

    在windows下安装配置Ulipad 由于UliPad 是由wxPython 开发的,所以,需要先安装wxPython . wxPython下载地址: http://www.wxpython.org ...

  6. python学习笔记(八):异常处理

    一.异常处理 在程序运行过程中,总会遇到各种各样的错误.程序一出错就停止运行了,那我们不能让程序停止运行吧,这时候就需要捕捉异常了,通过捕捉到的异常,我们再去做对应的处理. 下面我们先写一个函数,实现 ...

  7. Python学习笔记18:标准库之多进程(multiprocessing包)

    我们能够使用subprocess包来创建子进程.但这个包有两个非常大的局限性: 1) 我们总是让subprocess执行外部的程序,而不是执行一个Python脚本内部编写的函数. 2) 进程间仅仅通过 ...

  8. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  9. Python 学习笔记(下)

    Python 学习笔记(下) 这份笔记是我在系统地学习python时记录的,它不能算是一份完整的参考,但里面大都是我觉得比较重要的地方. 目录 Python 学习笔记(下) 函数设计与使用 形参与实参 ...

随机推荐

  1. 行人重识别(ReID) ——基于深度学习的行人重识别研究综述

    转自:https://zhuanlan.zhihu.com/p/31921944 前言:行人重识别(Person Re-identification)也称行人再识别,本文简称为ReID,是利用计算机视 ...

  2. no hash tools

    import itertools class Set(list):    def __init__(self, params):        super(Set, self).__init__()  ...

  3. JVM的内存区域划分(jdk7和jdk8)

    参考: https://blog.csdn.net/l1394049664/article/details/81486470?tdsourcetag=s_pctim_aiomsg https://bl ...

  4. Flutter-SearchDelegate搜索框

    搜索欄 import 'package:flutter/material.dart'; typedef SearchItemCall = void Function(String item); cla ...

  5. AIX下绑定双网卡

    摘要 AIX下绑定双网卡,实现IP地址的高可用.为后续按照oracle11gRAC环境做准备.   收 藏 生产环境中是将不同网卡的不同网口进行绑定.比如A网卡有A1,A2网口:B网卡有B1,B2网口 ...

  6. 关于scikit-learn

    机器学习scikit-learn scikit-learn官网学习资料非常丰富,完全可以自学: http://scikit-learn.org/ 目前就以scikit-learn为主要工具学习mach ...

  7. Redis基础系列-安装启动

    安装 ①将Redis 的tar 包上传到opt 目录②解压缩③安装gcc 环境我们需要将源码编译后再安装,因此需要安装c 语言的编译环境!不能直接make! 可以上网,yum install –y g ...

  8. 【leetcode】1072. Flip Columns For Maximum Number of Equal Rows

    题目如下: Given a matrix consisting of 0s and 1s, we may choose any number of columns in the matrix and ...

  9. 对props的研究

    Vue.component('my-component', { props: { // 基础的类型检查 (`null` 匹配任何类型) propA: Number, // 多个可能的类型 propB: ...

  10. git本地创建一个分支并上传到远程服务器上

    git branch 查看分支 新建分支:git checkout -b dev 把新建的本地分支push到远程服务器 git push origin 本地名字:外地名字 删除远程分支 git pus ...