python 处理异常

In our previous tutorial, we discussed about Python Directory. In this tutorial, we are going to learn Python Exception Handling. Python try except keywords are used for exception handling in python.

在上一教程中,我们讨论了Python目录 。 在本教程中,我们将学习Python异常处理。 Python尝试将关键字除外,但将其用于python中的异常处理。

Python异常处理 (Python Exception Handling)

Basically, exception means something that is not expected. In real life, we are not interested to deal with exceptions. So there goes a proverb, “Exception is not an example”. But when we write programs, we have to think about exceptional cases. For example, if your user entered a string object while you were expecting an integer object as input, it will raise an exception.

基本上,异常意味着不期望的事情。 在现实生活中,我们对处理异常不感兴趣。 因此有句谚语,“例外不是一个例子”。 但是,当我们编写程序时,我们必须考虑例外情况。 例如,如果您的用户在期望输入整数对象时输入了字符串对象,则将引发异常。

Exception hampers normal program flows. If any exception happens, the programmer needs to handle that. Therefore, we are going to learn exception handling in upcoming sections.

异常妨碍正常的程序流。 如果发生任何异常,程序员需要处理。 因此,我们将在接下来的部分中学习异常处理。

一些内置的Python异常 (Some Built-in Python Exceptions)

List of some built-in python exceptions are given below.

下面列出了一些内置的python异常。

  1. Exception : This is the base class for all kind of the exceptions. All kind of exceptions should be derived from this class异常:这是所有异常的基类。 各种异常都应从此类派生
  2. ArithmeticError : This is the base class for the exception raised for any arithmetic errors.ArithmeticError:这是任何算术错误引发的异常的基类。
  3. EOFError : This exception raise when input() function read End-of-File without reading any data.EOFError:当input()函数读取文件末尾而不读取任何数据时, 引发此异常。
  4. ZeroDivisionError : This exception raise when the second argument of a division or modulo operation is zeroZeroDivisionError:当除法或模运算的第二个参数为零时,将引发此异常
  5. AssertionError : This exception raise when an assert statement fails.AssertionError: 断言语句失败时引发此异常。
  6. FloatingPointError : This exception raise when a floating point operation fails.FloatingPointError:当浮点操作失败时,将引发此异常。
  7. KeyError : This exception raise when a mapping (dictionary) key is not found in the set of existing keys.KeyError:当在现有键集中找不到映射(字典)键时,引发此异常。
  8. KeyboardInterrupt : This exception raise when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly.KeyboardInterrupt:当用户按下中断键(通常为Control-C或Delete)时,引发此异常。 在执行期间,会定期检查中断。

Besides, you can find the list of all Built-in Exception in their official site.

此外,您可以在其官方网站上找到所有内置异常的列表。

Python尝试除外 (Python try except)

While writing the code, some statements might suspicious for raising an error. Hence, those statements should be surrounded with a try-except-else block. For example, we will now raise an exception by our code. The following code will raise IndexError Exception.

在编写代码时,某些语句可能会引起错误。 因此,这些语句应包含try-except-else块。 例如,我们现在将通过代码引发异常。 以下代码将引发IndexError Exception。

name = 'Imtiaz Abedin'
print(name[15])print('This will not print')

If you try running the code, you will get below exception.

如果您尝试运行代码,将得到以下异常。

Traceback (most recent call last):File "/home/imtiaz/ExceptionHandling.py", line 2, in print(name[15])
IndexError: string index out of range

Because the size of the string type object ‘name’ is less than 15 and we are trying to access the index no 15. Have a look, the second print statement is not executed for that exception. So program crashes due to an exception. So, in the next code, we will handle this exception.

因为字符串类型对象“名称”的大小小于15,并且我们正在尝试访问索引号15。请看一下,该异常不会执行第二个print语句。 因此程序由于异常而崩溃。 因此,在下一个代码中,我们将处理此异常。

name = 'Imtiaz Abedin'
try:print(name[15])
except IndexError:print('IndexError has been found!')print('This will be printed print.')

So, you can see from the above two examples that exception should be handled to avoid the program crash. In our first example, the last print statement was not executed because the program found exception before that. You can see that try except keywords are used for exception handling.

因此,从以上两个示例可以看出,应处理异常以避免程序崩溃。 在我们的第一个示例中,未执行最后一个print语句,因为程序在此之前发现了异常。 您可以看到try关键字除外用于异常处理。

Python异常处理的基本结构 (Basic Structure of Python Exception Handling)

In the previous section, we demonstrate how exception raised and how to handle that. In this section, we will discuss the basic coding structure for handling exceptions. Therefore, the basic coding structure for Python Exception Handling is given below.

在上一节中,我们演示了异常如何引发以及如何处理。 在本节中,我们将讨论用于处理异常的基本编码结构。 因此,下面给出了Python异常处理的基本编码结构。

name = 'Imtiaz Abedin'
try:# Write the suspicious block of codeprint(name[15])
except AssertionError:  # Catch a single exception# This block will be executed if exception A is caughtprint('AssertionError')
except (EnvironmentError, SyntaxError, NameError) as E:  # catch multiple exception# This block will be executed if any of the exception B, C or D is caughtprint(E)
except :print('Exception')# This block will be executed if any other exception other than A, B, C or D is caught
else:# If no exception is caught, this block will be executedpass
finally:# This block will be executed and it is a must!pass# this line is not related to the try-except block
print('This will be printed.')

Here you can see that, we use except keyword in different style. The first except keyword is used to catch only one exception that is AssertionError exception.

在这里您可以看到,我们以不同的样式使用了except关键字。 第一个except关键字仅用于捕获一个异常,即AssertionError异常。

However, the second except keyword is used to catch multiple exceptions, as you see.

但是,如您所见,第二个except关键字用于捕获多个异常。

If you use except keyword without mentioning any specific exception, it will catch any exception that is raised by the program.

如果使用except关键字而不提及任何特定的异常,它将捕获程序引发的任何异常。

The else block will be executed if no exception is found. Lastly, whether any exception is caught or not, the finally block will be executed.

如果未发现异常,则将执行else块。 最后,无论是否捕获到任何异常,都将执行finally块。

So, if you run the above code, we will get the output:

因此,如果运行上面的代码,我们将获得输出:

If you change ‘name[15]’ to ‘nameee[15]’ in the above code, you will get the following output.

如果在上面的代码中将“ name [15]”更改为“ nameee [15]”,您将得到以下输出。

Python异常处理要点 (Python Exception Handling Important Points)

For undergoing a professional python project you need to be careful about exceptions. A simple exception can ruin your code. So, you need to handle those exceptions. A few important points about handling exceptions are given below.

为了进行专业的python项目,您需要注意异常。 一个简单的异常会破坏您的代码。 因此,您需要处理这些异常。 以下是有关处理异常的一些重要点。

  1. It is better to surround the suspicious code with try-except.最好用try-except包围可疑代码。
  2. Using one try-except block for one line of suspicious code is better than using one try-except block for a block of suspicious code.对一行可疑代码使用一个try-except块比对一行可疑代码使用一个try-except块要好。
  3. It is better to catch specific exception class. Using generalized exception class is not that much useful for handling.最好捕获特定的异常类。 使用通用异常类对处理没有太大帮助。

So, that’s all for Python Exception Handling. Hope, that you understand well. For any query, please use the comment box. We will answer you.

因此,这就是Python异常处理的全部内容。 希望您理解得很好。 对于任何查询,请使用注释框。 我们将回答您。

翻译自: https://www.journaldev.com/14444/python-exception-handling-try-except

python 处理异常

python 处理异常_Python异常处理– Python尝试除外相关推荐

  1. python 处理异常_Python异常处理:

    python 处理异常 While the try and except block are for handling exceptions, the raise keyword on the con ...

  2. python下标越界异常_python异常处理

    异常处理 程序错误分为两种:语法错误 和 异常错误 语法错误:代码没有按照python规定语法去写,发明创造产生的错误 异常错误:在代码语法正确的前提下,程序报错就是异常 基础语法:try...exc ...

  3. python类型转换异常_python知识:json格式文本;异常处理;字符串处理;unicode类型和str类型转换...

    python进程中的实例和json格式的字符串之间的映射关系是非常直接的,相当于同一个概念被编码成不同的表示: stream in json form ----json.loads(str)----- ...

  4. python finally语句里面出现异常_Python异常处理中的else和finally

    Python语言可能是最接近人类能够自然理解的编程语言,但是编程语言跟人类语言有个非常明显的区别,那就是灵活性.人类语言很灵活,怎么说对方都能够理解,语法什么的,在日常对话中并不重要:但是用编程语言写 ...

  5. python断言失败_python异常处理、自定义异常、断言原理与用法分析

    本文实例讲述了python异常处理.自定义异常.断言原理与用法.分享给大家供大家参考,具体如下: 什么是异常: 当程序遭遇某些非正常问题的时候就会抛出异常:比如int()只能处理能转化成int的对象, ...

  6. python打印异常_python异常输出

    广告关闭 腾讯云11.11云上盛惠 ,精选热门产品助力上云,云服务器首年88元起,买的越多返的越多,最高返5000元! 开发准备cas 的 python sdk 包含了用于访问和操作 cas 的所有 ...

  7. python 忽略异常_关于python:如何正确地忽略异常

    当您只是想尝试-除非不处理异常,否则如何在Python中进行尝试? 下面的方法正确吗? try: shutil.rmtree(path) except: pass 奇怪的是直到现在还没有人提到它(我在 ...

  8. python ctypes教程_Python ctypes: Python file object - C FILE * | 易学教程

    可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I am using ctypes to wrap a C-library (which I ...

  9. python解释器调用_python入门-python解释器执行

    最近由于公司需要,接触了python这门神奇的语言,给我的感觉就是开发快速和代码简洁. 开始还是先罗列一下解释性语言和编译性语言的差别吧0.0! 编译性语言:是在程序运行前,需要专门的一个编译过程,如 ...

最新文章

  1. Spring Data JPA(官方文档翻译)
  2. Python基础02-序列及通用操作
  3. 第2章 Python 数字图像处理(DIP) --数字图像基础3 - 图像内插 - 最近邻内插 - 双线性插值 - 双三次内插 - 图像放大
  4. 长链接转短链接java_长链接生成短链接Java源码(调用百度接口)
  5. Invalid Gradle JDK configuration found_带你了解Gradle编译速度是如何提升70%的
  6. html 最小长度单位,html见长度单位尺寸单�?CSS布局HTML
  7. python语言中有3种表示字符串的方式、单引号和_Python中三种类型的引号(单引号、双引号、三引号)...
  8. solidwork 侵权 证据_电子商务法复习题
  9. perl语言得到的txt文档只有表头_编程语言排行榜第一Python,为何频繁遭受开发者的嫌弃!...
  10. 《穿越计算机的迷雾》读书笔记一
  11. 新版万能声卡驱动-VoodooHDA-2.8.5
  12. android+cardview用法,Android CardView的使用
  13. msyql创建数据库并指定字符集
  14. idea中html导入背景图片,IDEA设置导入主题样式皮肤,加入背景图片
  15. php实现12306验证码,PHP仿12306点图验证码
  16. PMP之项目质量管理
  17. leet234.回文链表
  18. 在线打包app平台以及流程平台分析(AndroidiOS)
  19. 验证短信延迟?是哪里出现问题
  20. 显示器与计算机主机无线连接,如何让手机、电脑和显示器无线连接

热门文章

  1. 进程/线程同步的方式和机制,进程间通信
  2. 基于Cookie的单点登录(SSO)系统介绍
  3. QQ抢车位外挂(起始篇)--小研究成果展示
  4. 了解Python编程——Python学习(一)
  5. [转载] 6.3 cmath--数学函数
  6. [转载] Python与其他语言结合的参数转换函数PyArg_ParseTuple()
  7. poi报表导出4.1.0版本工具类 导出并下载
  8. Linux文件上传下载sz 和 rz 命令
  9. React Native常用第三方汇总
  10. 工作六年的前端开发在想什么