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

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 zero

    ZeroDivisionError:当除法或模运算的第二个参数为零时,将引发此异常
  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 code
   print(name[15])
except AssertionError:  # Catch a single exception
   # This block will be executed if exception A is caught
   print('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 caught
   print(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 executed
   pass
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 处理异常

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值