python异常处理

Exception handling is a concept used in Python to handle the exceptions and errors that occur during the execution of any program. Exceptions are unexpected errors that can occur during code execution. We have covered about exceptions and errors in python in the last tutorial.

异常处理是Python中用于处理任何程序执行期间发生的异常和错误的概念。 异常是代码执行期间可能发生的意外错误。 在上一教程中,我们讨论了python中的异常和错误

Well, yes, exception occur, there can be errors in your code, but why should we invest time in handling exceptions?

好吧,是的,发生异常,您的代码中可能有错误,但是为什么我们要花时间来处理异常?

The answer to this question is to improve User Experience. When an exception occurs, following things happen:

这个问题的答案是改善用户体验 。 发生异常时,会发生以下情况:

  • Program execution abruptly stops.

    程序执行突然停止。

  • The complete exception message along with the file name and line number of code is printed on console.

    完整的异常消息以及文​​件名和代码行号将打印在控制台上。

  • All the calculations and operations performed till that point in code are lost.

    直到该代码点为止执行的所有计算和操作都将丢失。

Now think that one day you are using Studytonight's website, you click on some link to open a tutorial, which, for some unknown reason, leads to some exception. If we haven't handled the exceptions then you will see exception message while the webpage is also not loaded. Will you like that?

现在以为有一天,您在使用Studytonight的网站时,单击某个链接以打开一个教程,由于某种未知的原因,该教程会导致某些异常。 如果我们没有处理异常,那么当网页也未加载时,您会看到异常消息。 你会喜欢吗?

Hence, exception handling is very important to handle errors gracefully and displaying appropriate message to inform the user about the malfunctioning.

因此,异常处理对于优雅地处理错误并显示适当的消息以告知用户有关故障非常重要。

使用tryexcept处理异常 (Handling Exceptions using try and except)

For handling exceptions in Python we use two types of blocks, namely, try block and except block.

为了在Python中处理异常,我们使用两种类型的块,即try块和except块。

In the try block, we write the code in which there are chances of any error or exception to occur.

try块中,我们编写了可能发生任何错误或异常的代码。

Whereas the except block is responsible for catching the exception and executing the statements specified inside it.

except块负责捕获异常并执行其内部指定的语句。

Below we have the code performing division by zero:

下面我们执行零除的代码:

a = 10
b = 0
print("Result of Division: " + str(a/b))

Traceback (most recent call last): File "main.py", line 3, in <module> print("Result of Division: " + str(a/b)) ZeroDivisionError: division by zero

追溯(最近一次调用最近):文件“ main.py”,第3行,位于<module> print(“除法结果:” + str(a / b))ZeroDivisionError:被零除

The above code leads to exception and the exception message is printed as output on the console.

上面的代码导致异常,并且异常消息将作为输出打印在控制台上。

If we use the try and except block, we can handle this exception gracefully.

如果使用tryexcept块,则可以正常处理此异常。

# try block
try:a = 10b = 0print("Result of Division: " + str(a/b))
except:print("You have divided a number by zero, which is not allowed.")

You have divided a number by zero, which is not allowed.

您已将数字除以零,这是不允许的。

try块 (The try block)

As you can see in the code example above, the try block is used to put the whole code that is to be executed in the program(which you think can lead to exception), if any exception occurs during execution of the code inside the try block, then it causes the execution of the code to be directed to the except block and the execution that was going on in the try block is interrupted. But, if no exception occurs, then the whole try block is executed and the except block is never executed.

如您在上面的代码示例中所看到的,如果在try中执行代码期间发生任何异常,则try块用于将要执行的整个代码放入程序中(您认为这会导致异常)。块,然后将代码的执行定向到except块,并且try块中正在进行的执行被中断。 但是,如果没有异常发生,则将执行整个try块,并且永远不会执行except块。

except块 (The except block)

The try block is generally followed by the except block which holds the exception cleanup code(exception has occured, how to effectively handle the situation) like some print statement to print some message or may be trigger some event or store something in the database etc.

try块之后通常是except块,该异常块包含异常清除代码( 发生了异常,如何有效处理情况 ),例如一些print语句以打印某些消息,或者可能触发某些事件将某些内容存储在数据库中,等等。

In the except block, along with the keyword except we can also provide the name of exception class which is expected to occur. In case we do not provide any exception class name, it catches all the exceptions, otherwise it will only catch the exception of the type which is mentioned.

except块中 ,连同关键字except我们还可以提供预期发生的异常类名称 。 如果我们不提供任何异常类名,它将捕获所有异常,否则将仅捕获所提及类型的异常。

Here is the syntax:

这是语法

# except block
except(<Types of Exceptions to catched>):# except block starts

If you notice closely, we have mentioned types of exceptions, yes, we can even provide names of multiples exception classes separated by comma in the except statement.

如果您密切注意,我们已经提到了异常类型 ,是的,我们甚至可以在except语句中提供多个以逗号分隔的异常类的名称。

except块之后,代码执行继续 (Code Execution continues after except block)

Another important point to note here is that code execution is interrupted in the try block when an exception occurs, and the code statements inside the try block after the line which caused the exception are not executed.

这里要注意的另一个重要点是,发生异常时, try块中的代码执行会中断,并且导致异常的行之后try块中的代码语句不会执行。

The execution then jumps into the except block. And after the execution of the code statements inside the except block the code statements after it are executed, just like any other normal execution.

然后执行跳入except块。 在except块内执行代码语句之后,像执行任何其他常规执行一样,执行之后的代码语句。

Let's take an example:

让我们举个例子:

# try block
try:a = 10b = 0print("Result of Division: " + str(a/b))print("No! This line will not be executed.")
except:print("You have divided a number by zero, which is not allowed.")# outside the try-except blocks
print("Yo! This line will be executed.")

You have divided a number by zero, which is not allowed. Yo! This line will be executed.

您已将数字除以零,这是不允许的。 ! 这行将被执行。

在Python中捕获多个异常 (Catching Multiple Exceptions in Python)

There are multiple ways to accomplish this. Either we can have multiple except blocks with each one handling a specific exception class or we can handle multiple exception classes in a single except block.

有多种方法可以实现此目的。 我们可以有多个except块,每个except块都处理一个特定的异常类,或者我们可以在一个except块中处理多个例外类。

多个except块 (Multiple except blocks)

If you think your code may generate different exceptions in different situations and you want to handle those exceptions individually, then you can have multiple except blocks.

如果您认为您的代码在不同情况下可能会生成不同的异常,并且希望分别处理这些异常,则可以有多个except块。

Mostly exceptions occur when user inputs are involved. So let's take a simple example where we will ask user for two numbers to perform division operation on them and show them the result.

通常,涉及用户输入时会发生异常。 因此,让我们举一个简单的示例,在该示例中,我们将要求用户输入两个数字以对其进行除法运算并向其显示结果。

We will try to handle multiple possible exception cases using multiple except blocks.

我们将尝试使用多个except块来处理多种可能的异常情况。

演示地址

Try running the above code, provide 0 as value for the denominator and see what happens and then provide some string(non-integer) value for any variable. We have handled both the cases in the above code.

尝试运行以上代码,为分母提供0作为值,看看会发生什么,然后为任何变量提供一些字符串 (非整数)值。 我们已经在上面的代码中处理了两种情况。

处理多个异常与except块 (Handling Multiple Exceptions with on except block)

As you can see in the above example we printed different messages based on what exception occured. If you do not have such requirements where you need to handle different exception individually, you can catch a set of exceptions in a single exception block as well.

如您在上面的示例中看到的,我们根据发生的异常情况打印了不同的消息。 如果您没有这样的要求,需要单独处理不同的异常,则也可以在单个异常块中捕获一组异常。

Here is above the above code with a single except block:

这是在上面的代码上方,带有一个except块:

# try block
try:a = int(input("Enter numerator number: "))b = int(input("Enter denominator number: "))print("Result of Division: " + str(a/b))
# except block handling division by zero
except(ValueError, ZeroDivisionError):print("Please check the input value: It should be an integer greater than 0")

here we have handled both the exceptions using a single except block while showing a meaningful message to the user.

在这里,我们在向用户显示有意义的消息的同时,使用了一个单独的except块来处理这两种异常。

通用except块,用于处理未知异常 (Generic except block to Handle unknown Exceptions)

Although we do try to make our code error free by testing it and using exception handling but there can be some error situation which we might have missed.

尽管我们确实尝试通过测试代码和使用异常处理来使我们的代码无错误,但是可能会遗漏一些错误情况。

So when we use except blocks to handle specific exception classes we should always have a generic except block at the end to handle any runtime excpetions(surprise events).

因此,当我们使用except块来处理特定的异常类时,我们应该始终在末尾使用通用的 except块来处理任何运行时异常(意外事件)。

# try block
try:a = int(input("Enter numerator number: "))b = int(input("Enter denominator number: "))print("Result of Division: " + str(a/b))
# except block handling division by zero
except(ZeroDivisionError):print("You have divided a number by zero, which is not allowed.")
# except block handling wrong value type
except(ValueError):print("You must enter integer value")
# generic except block
except:print("Oops! Something went wrong!")

In the code above the first except block will handle the ZeroDivisionError, second except block will handle the ValueError and for any other exception that might occur we have the third except block.

在上面的代码中,第一个except块将处理ZeroDivisionError ,第二个except块将处理ValueError ,对于可能发生的任何其他异常,我们有第三个except块。

In the coming tutorials we will learn about finally block and how to raise an exception using the raise keyword.

在接下来的教程中,我们将学习有关finally块以及如何使用raise关键字引发异常的信息。

翻译自: https://www.studytonight.com/python/exception-handling-python

python异常处理

python异常处理_Python异常处理相关推荐

  1. python超出范围异常处理_Python异常处理

    一异常和错误 1 程序中难免出现错误,而错误分成两种 1.语法错误(这种错误,根本过不了Python解释器的语法检测,必须在程序执行前就改正) 语法错误 语法错误示范一 if 语法错误示范二 def ...

  2. python异常处理输入不是整数_Python异常处理大全(二)

    本文是Python异常处理教程的第二部分,上部分我们简单的介绍了几种异常,及其处理办法,这部分我们将更详细地对Python中产生的异常处理方法进行探讨. 函数使用异常 看看这个: 如果some_fun ...

  3. 在python中、如果异常并未被处理或捕捉_Python异常处理总结

    本文较为详细的罗列了Python常见的异常处理,供大家参考,具体如下: 1. 抛出异常和自定义异常 Python用异常对象(exception object)表示异常情况,遇到错误后,会引发异常.如果 ...

  4. python 处理异常_Python异常处理– Python尝试除外

    python 处理异常 In our previous tutorial, we discussed about Python Directory. In this tutorial, we are ...

  5. python抛出异常的关键字_Python异常处理总结

    本文较为详细的罗列了Python常见的异常处理,供大家参考,具体如下: 1. 抛出异常和自定义异常 Python用异常对象(exception object)表示异常情况,遇到错误后,会引发异常.如果 ...

  6. python如何处理异常退出_python异常处理

    一.错误和异常 1.错误 代码运行前的语法或者逻辑错误 语法错误(这种错误,根本过不了python解释器的语法检测,必须在程序执行前就改正) def test: ^ SyntaxError: inva ...

  7. python网络编程-异常处理-异常捕获-抛出异常-断言-自定义异常-UDP通信-socketserver模块应用-03

    python网络编程-异常处理-异常捕获-抛出异常-断言-自定义异常-UDP通信-socketserver模块应用-03 参考文章: (1)python网络编程-异常处理-异常捕获-抛出异常-断言-自 ...

  8. python基础之异常处理

    python基础之异常处理 参考文章: (1)python基础之异常处理 (2)https://www.cnblogs.com/zhangyux/p/6108026.html (3)https://w ...

  9. python错误-python错误和异常处理怎处理你知道么

    原标题:python错误和异常处理怎处理你知道么 异常处理 什么是异常? 首先要清楚,什么是异常,异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常 ...

最新文章

  1. (转) Twisted :第十八部分 Deferreds 全貌
  2. Spring的静态代理和动态代理
  3. (chap6 Http首部) 响应首部字段 Accept-RangeAge Etag
  4. Yolo-v2 Visual Studio 2015安装时报错Team Explorer for Microsoft Visual Studio 2015解决办法
  5. python opencv屏幕找图_使用Python+OpenCV进行图像模板匹配(Match Template)实例-找到百度首页按钮并点击...
  6. mysql scope runtime_maven scope provided和runtime的例子
  7. mysql数据库开发环境_MacOS下搭载开发环境之数据库篇(Mysql + Navicat)
  8. django-中间件0911-2
  9. 资源放送丨《Oracle存储过程性能分析案例》PPT视频
  10. python百分比堆积条形图_Pandas 堆积条形图中的元素顺序 - python
  11. react antd 更改table 表头和表行样式
  12. (day 17 - 快排)剑指 Offer 40. 最小的k个数
  13. [淘宝商城首页]-图片灯箱明暗遮罩效果之jquery版
  14. ROS:ModuleNotFoundError: No module named ‘rospkg‘
  15. 漫画算法python版下载_漫画算法:小灰的算法之旅(Python篇)
  16. java对数据库的基础知识
  17. [SCU 4507] 奶牛情书 (AC自动机)
  18. 戴尔服务器技术响应表,戴尔PowerEdge T110 II产品技术白皮书
  19. 荣耀play5t活力版和荣耀畅玩20哪个好 哪个更值得入手
  20. python urldecode_Python 爬虫笔记2一(编码转码urlencode与unquote)

热门文章

  1. C# Excel 数据导入mysql数据库
  2. 2022中国眼博会,山东眼健康展,视力矫正仪器展,护眼产品展
  3. 易度,企业中的蓝胖子
  4. Android颜色对照表
  5. 当电脑开不了机出现自动修复时
  6. 暗通道去雾(何恺明的成名作):简洁与效果并存的传统图像处理算法
  7. 日历 fullCalendar 整合农历
  8. git 安装后,右键没有 git clone
  9. 湖南中烟计算机专业考试,2018湖南中烟招聘笔试题目,2019笔试内容
  10. 关于Mac软件不兼容的解决方案(xattr)