python在哪里编写代码_如何在Python中使用异常处理编写不可阻挡的代码

python在哪里编写代码

Fighting against the errors in code is the most important part of every programmer’s life. In fact, the errors you are making will be your best teacher in programming. Sometimes, the code will undergo some unexpected situations while executing the code. When the interpreter or compiler could not able to proceed further it will send some error message to the output screen. In python, the error message is known as an exception.

对抗代码错误是每个程序员生命中最重要的部分。 实际上,您所犯的错误将是您编程中最好的老师。 有时,代码在执行代码时会遇到一些意外情况。 当解释器或编译器无法继续进行操作时,它将向输出屏幕发送一些错误消息。 在python中,错误消息称为异常。

有什么例外? (What is an exception?)

If you are a beginner in the programming you may come across many errors in programs. The errors are both worst and best thing in programming. The worst part is that the error makes your program to end before the complete execution. The best thing is errors teach you what not to do while writing code.

如果您是编程的初学者,则可能会在程序中遇到许多错误。 错误在编程中既是最糟糕的也是最好的事情。 最糟糕的部分是该错误使您的程序在完全执行之前结束。 最好的事情是错误会教您在编写代码时不要做什么。

The process of making your code to execute properly without any error is called exception handling. To handle the exception, the programmer must develop their ability to predict where and what type of error can occur.

使代码正确执行而没有任何错误的过程称为异常处理。 为了处理异常,程序员必须增强其能力,以预测可能在何处以及哪种类型的错误发生。

异常处理的起源 (Origin of exception handling)

At the beginning of the history of programming, programmers were searching for a solution that can prevent their code to end in the middle of execution. The errors occurred not only in the test codes but also it affected many hardware operations. The concept of handling exception evolved in the 1960s in a language called Lisp.

在编程历史的开始,程序员一直在寻找一种解决方案,以防止其代码在执行过程中结束。 这些错误不仅发生在测试代码中,而且还影响了许多硬件操作。 处理异常的概念在1960年代演变为一种称为Lisp的语言。

The concept started to gain more functionalities like catching the exception and creating our own exception in the period of 1960 to 1975. Now it is being a very essential feature among most common programming languages and operating systems.

在1960年至1975年期间,该概念开始获得更多功能,例如捕获异常和创建我们自己的异常。现在,它已成为大多数通用编程语言和操作系统中非常重要的功能。

Python中的异常 (Exceptions in Python)

When an interpreter goes under unusual situations or unaware about the syntax written it will throw a message which explains the user about what’s gone wrong with the code. Actually, the exception in python prevents the code from the crash. The codes written after the line where the error occurred will not be executed by the interpreter.

当解释器遇到异常情况或不了解所编写的语法时,它将抛出一条消息,向用户解释代码出了什么问题。 实际上,python中的异常可防止代码崩溃。 发生错误的行之后写入的代码将不会由解释器执行。

常见问题 (A Common Problem)

As we learned in our elementary classes, zero cannot divide any number. This is a universal truth in mathematics. Computers not an exemption in it. Let us write a code in python to get two integers from the users and print the value of the division.

正如我们在小学班级中学到的,零不能除以任何数字。 这是数学中的普遍真理。 电脑不是其中的一项豁免。 让我们用python编写代码以从用户那里获取两个整数并打印除法的值。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))print(Number_A / Number_B)

I’ve executed the code with two cases of inputs. Lets the inputs be Case1 (25,5) and Case 2 (25,0). Look at the outputs below.

我已经用两种情况输入了代码。 假设输入为Case1 (25,5)和Case 2 (25,0)。 查看下面的输出。

Case 1

情况1

Enter Value A:25
Enter Value B:5
5.0

Case 2

情况二

Enter Value A:25
Enter Value B:0
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(Number_A / Number_B)ZeroDivisionError: division by zero

As the second input made the interpreter make a decision about dividing with zero, the python interpreter threw an exception in the console. The actual exception statement is highlighted in the Case2 output.

当第二个输入使解释器决定除以零时,python解释器在控制台中引发了异常。 实际的异常语句在Case2输出中突出显示。

豁免后发生了什么事 (What’s happening after an exemption)

Let us try to modify the previous code by adding some extra code with that. We can use the same inputs for this program too.

让我们尝试通过添加一些额外的代码来修改之前的代码。 我们也可以为该程序使用相同的输入。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))print(Number_A / Number_B)print("The program reached the end")

Case 1

情况1

Enter Value A:25
Enter Value B:5
5.0
The program reached the end

Case 2

情况二

Enter Value A:25
Enter Value B:0
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(Number_A / Number_B)
ZeroDivisionError: division by zero

In the second execution of the code get stopped where the error occurred. That means the lines after the error is not executed. This is the major reason to handle the exception.

在代码的第二次执行中,在发生错误的地方停止。 这意味着不会执行错误后的行。 这是处理该异常的主要原因。

Python中的各种异常 (Various Exceptions in Python)

In this section of the tutorial, we will see some basic exceptions used in python programming. Each exception is explained with proper code examples. Some exceptions explained are listed below.

在本教程的这一部分中,我们将看到python编程中使用的一些基本异常。 每个异常都通过适当的代码示例进行了说明。 下面列出了一些解释的例外情况。

  • Syntax Errors

    语法错误
  • Type Error

    类型错误
  • Import Error

    导入错误
  • Value Error

    值错误
  • Index Error

    索引错误
  • Key Error

    关键错误
  • Name Error

    名称错误

Syntax Error

语法错误

Syntax errors occur when the program contains wrong syntax in it. The parser of the python always looks for a perfect syntax everywhere. It is very usual for beginners to make mistakes in syntax. Continues practice will help the programmer to reduce the syntax error.

当程序中包含错误的语法时,就会发生语法错误。 python的解析器始终在各处寻找完美的语法。 对于初学者来说,语法错误是很常见的。 继续练习将有助于程序员减少语法错误。

message = "This is a message"
print(message

Output

输出量

File "main.py", line 3

^
SyntaxError: unexpected EOF while parsing

Type Error

类型错误

Type error occurs when the code trying to perform an operation inappropriate of the type. Addition of two numbers is possible while adding one number to a string is not possible. This will create an type error in python.

当代码尝试执行不适合该类型的操作时,将发生类型错误。 可以添加两个数字,而不能将一个数字添加到字符串中。 这将在python中创建类型错误。

text = "This is a text"
number = 25print(text + number)

Output

输出量

Traceback (most recent call last):
File "main.py", line 3, in <module>
print(text + number)
TypeError: Can't convert 'int' object to str implicitly

Import Error

导入错误

To import a module to your program the modules should be installed in pythons modules directory. When a programmer tries to import a module that is not present in the python it will create import error. It works with the error called ModuleNotFoundError.

要将模块导入程序,应将模块安装在pythons modules目录中。 当程序员尝试导入python中不存在的模块时,它将创建导入错误。 它可以处理名为ModuleNotFoundError的错误。

import nump
print("Hello")

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 1, in <module>
import nump
ModuleNotFoundError: No module named 'nump'

Value Error

值错误

Some operations in python can be applied to only certain type of data. When someone tries to perform a task on different types of data it will throw a value error in Python. For example, the conversion of a string containing alphabets cannot be converted to numbers.

python中的某些操作只能应用于某些类型的数据。 当有人尝试对不同类型的数据执行任务时,它将在Python中引发值错误。 例如,包含字母的字符串的转换不能转换为数字。

text = "123A"
print(int(text))

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 2, in <module>
print(int(text))
ValueError: invalid literal for int() with base 10: '123A'

Index Error

索引错误

Index error occurs in sequence type of data. This happens when the use trying to access the value at an index which is not available in the collection. The following code example will help you understand the Index Error.

数据的序列类型发生索引错误。 当用户尝试访问集合中不可用的索引处的值时,会发生这种情况。 以下代码示例将帮助您了解索引错误。

array = [0, 1, 4, 6, 7]
print(array[7])

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 2, in <module>
print(array[7])
IndexError: list index out of range

Key Error

关键错误

Key error is an error that occurs in dictionary data type. If the user tries to access a value in a dictionary by a key that is not present in dictionary it will create a key error in python.

键错误是在字典数据类型中发生的错误。 如果用户尝试通过字典中不存在的键访问字典中的值,则会在python中创建键错误。

dictionary = {'A':1, 'B':2, 'C':3}
print(dictionary['D'])

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 2, in <module>
print(dictionary['D'])
KeyError: 'D'

Name Error

名称错误

When we use a variable name that is not declared already the expression will create a name error. It mostly occurs when the programmer is not taking care of the case of variable name or making some spelling mistakes.

当我们使用尚未声明的变量名称时,表达式将创建名称错误。 它通常在程序员不注意变量名或拼写错误的情况下发生。

number = 25
print(Number)

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 2, in <module>
print(Number)
NameError: name 'Number' is not defined

So far, we have only discussed the common errors in python. The following tree will show all the exception under a class.

到目前为止,我们仅讨论了python中的常见错误。 下面的树将显示一个类下的所有异常。

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
+-- ResourceWarn

To read the full documentation about exception follow the link.

要阅读有关异常的完整文档,请单击链接。

出现多个错误会怎样? (What happens with multiple errors?)

If a program contains more than one error then the very first error will create the exception in that. Look at the following sample for the multiple errors.

如果程序包含多个错误,则第一个错误将在其中创建异常。 请查看以下示例,以了解多个错误。

print(Name)
print(int("123A"))

Output

输出量

Traceback (most recent call last):
File "C:/Users/ELCOT/AppData/Local/Programs/Python/Python37/test.py", line 1, in <module>
print(Name)
NameError: name 'Name' is not defined

如何捕获异常? (How to capture an exception?)

The keywords try and except are very useful in the concept of exception handling. The keyword try is used to write the code that can make an exception during execution. Let us try to write a program for dividing two numbers.

关键字tryexcept在异常处理的概念中非常有用。 关键字try用于编写可以在执行期间引起异常的代码。 让我们尝试编写一个将两个数相除的程序。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
Number_C = Number_A / Number_Bexcept:
print("An Error Occured")

Case 1 — (25, 5)

案例1 —(25,5)

Enter Value A:25
Enter Value B:0

Case 2 — (25, 0)

案例2-(25,0)

Enter Value A:25
Enter Value B:0
An Error Occured

The code written inside the try snippet will be interpreted by the interpreter. When there is no error in the code like first test case the statements in except will not be executed. But in the second test case, there will be an Division By Zero error. So the statement inside the except part is executed.

try片段中编写的代码将由解释器解释。 当像第一个测试用例这样的代码中没有错误时,except中的语句将不会执行。 但是在第二个测试用例中,将存在“被零除”错误。 因此,执行except部分中的语句。

Let us try the try keyword with print statement in the same program with first test case.

让我们在第一个测试用例的同一程序中try使用带有print语句的try关键字。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
print(Number_A / Number_B)except:
print("An Error Occured")

Output

输出量

Enter Value A:25
Enter Value B:5
5.0

The statements under try keyword is working properly. In this program we made the code to write our own exception.

try关键字下的语句正常运行。 在此程序中,我们编写了代码以编写我们自己的异常。

程序中的多重异常 (Multiple Exception in a Program)

In the previous program the error may be anything. Sometimes, we can expect more than one error for a particular line of code. The same code may produce Zero Division error as well as Name error. We can use multiple except statements to throw a different exception for a different type of error.

在先前的程序中,错误可能是任何错误。 有时,对于特定的代码行,我们可能会期望多个错误。 相同的代码可能会产生零分错误以及名称错误。 我们可以使用多个except语句针对不同类型的错误引发不同的异常。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
print(Number_A / Number_C)except ZeroDivisionError:
print("The Zero Division Error Occurred")except NameError:
print("The Name Error Occurred")

Output

输出量

Enter Value A:25
Enter Value B:0
The Name Error Occurred

如果一切顺利怎么办? (What If Everything Goes Well?)

We can create many exceptions in a program. We know that the statements under try keyword will be executed properly when there is no error. But, if we need to do something when there is no error in the try statement, we should use else keyword. The else block is executed when the try block works properly. Let us take the same problem here.

我们可以在程序中创建许多异常。 我们知道,在没有错误的情况下, try关键字下的语句将正确执行。 但是,如果在try语句没有错误的情况下需要执行某些操作,则应使用else关键字。 当try块正常工作时, else块将被执行。 让我们在这里处理同样的问题。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
print(Number_A / Number_B)except ZeroDivisionError:
print("The Zero Division Error Occurred")except NameError:
print("The Name Error Occurred")else:
print("Completed Successfully")

Case 1 — (25, 0)

情况1 —(25,0)

Enter Value A:25
Enter Value B:0
The Zero Division Error Occurred

Case 2 — (25, 5)

案例2 —(25,5)

Enter Value A:25
Enter Value B:5
5.0
Completed Successfully

最后的关键字 (The finally Keyword)

The finally keyword works the same as the else clause explained in the previous section. But only thing is, the finally clause will be executed for sure. The finally clause does not care about whether there is an error or not.

finally关键字的功能与上一节中说明的else子句相同。 但是唯一的是, finally子句将确保执行。 finally子句不关心是否存在错误。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
print(Number_A / Number_B)except ZeroDivisionError:
print("The Zero Division Error Occurred")except NameError:
print("The Name Error Occurred")finally:
print("Completed Successfully")

Case 1 — (25, 0)

情况1 —(25,0)

Enter Value A:25
Enter Value B:0
The Zero Division Error Occurred
Completed Successfully

Case 2 — (25, 5)

案例2 —(25,5)

Enter Value A:25
Enter Value B:5
5.0
Completed Successfully

使用原始异常 (Using Original Exception)

Creating own exception does not mean, the actual exceptions are harmful. We can use the original exception directly using as keyword in except clause. This will print the original exception message.

创建自己的异常并不意味着实际的异常是有害的。 我们可以在except子句中直接使用原始异常as关键字。 这将打印原始的异常消息。

Number_A = int(input("Enter Value A:"))
Number_B = int(input("Enter Value B:"))try:
print(Number_A / Number_B)except ZeroDivisionError as x:
print("The Message is:",x)except NameError as y:
print("The Message is:",y)finally:
print("Completed Successfully")

Output

输出量

Enter Value A:25
Enter Value B:0
The message is:division by zero
Completed Successfully

Thank you all for reading this article. I hope you have learned something useful in this article. Do continuous practice on exception handling to make your code unstoppable during execution. I have listed other useful articles here. Please make use of them. You can follow me on Medium.com.

谢谢大家阅读本文。 希望您在本文中学到了一些有用的东西。 对异常处理进行连续练习,以使代码在执行过程中不可阻挡。 我在这里列出了其他有用的文章。 请利用它们。 您可以在Medium.com上关注我。

翻译自: https://levelup.gitconnected.com/how-to-write-unstoppable-codes-with-exception-handling-in-python-be5534b098b7

python在哪里编写代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值