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 aboutexceptions and errors in pythonin 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 isto 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 usingStudytonight'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.
因此,异常处理对于优雅地处理错误并显示适当的消息以告知用户有关故障非常重要。
使用try
和except
处理异常 (Handling Exceptions usingtry
andexcept
)
For handling exceptions in Python we use two types of blocks, namely,try
block andexcept
block.
为了在Python中处理异常,我们使用两种类型的块,即try
块和except
块。
In thetry
block, we write the code in which there are chances of any error or exception to occur.
在try
块中,我们编写了可能发生任何错误或异常的代码。
Whereas theexcept
block is responsible for catching the exception and executing the statements specified inside it.
而except
块负责捕获异常并执行其内部指定的语句。
Below we have the code performingdivision by zero:
下面我们执行零除的代码:
a = 10b = 0print("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 thetry
andexcept
block, we can handle this exception gracefully.
如果使用try
和except
块,则可以正常处理此异常。
# try blocktry: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
块 (Thetry
block)
As you can see in the code example above, thetry
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 thetry
block, then it causes the execution of the code to be directed to theexcept
block and the execution that was going on in thetry
block is interrupted. But, if no exception occurs, then the wholetry
block is executed and theexcept
block is never executed.
如您在上面的代码示例中所看到的,如果在try
中执行代码期间发生任何异常,则try
块用于将要执行的整个代码放入程序中(您认为这会导致异常)。块,然后将代码的执行定向到except
块,并且try
块中正在进行的执行被中断。 但是,如果没有异常发生,则将执行整个try
块,并且永远不会执行except
块。
except
块 (Theexcept
block)
Thetry
block is generally followed by theexcept
block which holds the exception cleanup code(exception has occured, how to effectively handle the situation) like someprint
statement toprint some messageor may betrigger some eventorstore something in the databaseetc.
在try
块之后通常是except
块,该异常块包含异常清除代码(发生了异常,如何有效处理情况),例如一些print
语句以打印某些消息,或者可能触发某些事件或将某些内容存储在数据库中,等等。
In theexcept block, along with the keywordexcept
we can also provide thename of exception classwhich 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 thesyntax:
这是语法:
# except blockexcept(<Types of Exceptions to catched>):# except block starts
If you notice closely, we have mentionedtypes of exceptions, yes, we can even provide names of multiples exception classes separated by comma in theexceptstatement.
如果您密切注意,我们已经提到了异常类型,是的,我们甚至可以在except语句中提供多个以逗号分隔的异常类的名称。
except
块之后,代码执行继续 (Code Execution continues afterexcept
block)
Another important point to note here is that code execution is interrupted in thetry
block when an exception occurs, and the code statements inside thetry
block after the line which caused the exception are not executed.
这里要注意的另一个重要点是,发生异常时,try
块中的代码执行会中断,并且导致异常的行之后try
块中的代码语句不会执行。
The execution then jumps into theexcept
block. And after the execution of the code statements inside theexcept
block the code statements after it are executed, just like any other normal execution.
然后执行跳入except
块。 在except
块内执行代码语句之后,像执行任何其他常规执行一样,执行之后的代码语句。
Let's take an example:
让我们举个例子:
# try blocktry: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 blocksprint("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 multipleexcept
blocks with each one handling a specific exception class or we can handle multiple exception classes in a singleexcept
block.
有多种方法可以实现此目的。 我们可以有多个except
块,每个except
块都处理一个特定的异常类,或者我们可以在一个except
块中处理多个例外类。
多个except
块 (Multipleexcept
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 multipleexcept
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 multipleexcept
blocks.
我们将尝试使用多个except
块来处理多种可能的异常情况。
演示地址
Try running the above code, provide0as value for the denominator and see what happens and then provide somestring(non-integer) value for any variable. We have handled both the cases in the above code.
尝试运行以上代码,为分母提供0作为值,看看会发生什么,然后为任何变量提供一些字符串(非整数)值。 我们已经在上面的代码中处理了两种情况。
处理多个异常与except
块 (Handling Multiple Exceptions with onexcept
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 singleexcept
block:
这是在上面的代码上方,带有一个except
块:
# try blocktry:a = int(input("Enter numerator number: "))b = int(input("Enter denominator number: "))print("Result of Division: " + str(a/b))# except block handling division by zeroexcept(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 singleexcept
block while showing a meaningful message to the user.
在这里,我们在向用户显示有意义的消息的同时,使用了一个单独的except
块来处理这两种异常。
通用except
块,用于处理未知异常 (Genericexcept
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 useexcept
blocks to handle specific exception classes we should always have agenericexcept
block at the end to handle any runtime excpetions(surprise events).
因此,当我们使用except
块来处理特定的异常类时,我们应该始终在末尾使用通用的except
块来处理任何运行时异常(意外事件)。
# try blocktry:a = int(input("Enter numerator number: "))b = int(input("Enter denominator number: "))print("Result of Division: " + str(a/b))# except block handling division by zeroexcept(ZeroDivisionError):print("You have divided a number by zero, which is not allowed.")# except block handling wrong value typeexcept(ValueError):print("You must enter integer value")# generic except blockexcept:print("Oops! Something went wrong!")
In the code above the firstexcept
block will handle theZeroDivisionError, secondexcept
block will handle theValueErrorand for any other exception that might occur we have the thirdexcept
block.
在上面的代码中,第一个except
块将处理ZeroDivisionError,第二个except
块将处理ValueError,对于可能发生的任何其他异常,我们有第三个except
块。
In the coming tutorials we will learn aboutfinally
block and how to raise an exception using theraise
keyword.
在接下来的教程中,我们将学习有关finally
块以及如何使用raise
关键字引发异常的信息。
翻译自: /python/exception-handling-python
python异常处理