600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python异常处理_Python异常处理

python异常处理_Python异常处理

时间:2019-11-08 08:00:11

相关推荐

python异常处理_Python异常处理

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.

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

使用tryexcept处理异常 (Handling Exceptions usingtryandexcept)

For handling exceptions in Python we use two types of blocks, namely,tryblock andexceptblock.

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

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

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

Whereas theexceptblock 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 thetryandexceptblock, we can handle this exception gracefully.

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

# 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块 (Thetryblock)

As you can see in the code example above, thetryblock 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 thetryblock, then it causes the execution of the code to be directed to theexceptblock and the execution that was going on in thetryblock is interrupted. But, if no exception occurs, then the wholetryblock is executed and theexceptblock is never executed.

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

except块 (Theexceptblock)

Thetryblock is generally followed by theexceptblock which holds the exception cleanup code(exception has occured, how to effectively handle the situation) like someprintstatement toprint some messageor may betrigger some eventorstore something in the databaseetc.

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

In theexcept block, along with the keywordexceptwe 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 afterexceptblock)

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

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

The execution then jumps into theexceptblock. And after the execution of the code statements inside theexceptblock 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 multipleexceptblocks with each one handling a specific exception class or we can handle multiple exception classes in a singleexceptblock.

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

多个except块 (Multipleexceptblocks)

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

如果您认为您的代码在不同情况下可能会生成不同的异常,并且希望分别处理这些异常,则可以有多个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 multipleexceptblocks.

我们将尝试使用多个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 onexceptblock)

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 singleexceptblock:

这是在上面的代码上方,带有一个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 singleexceptblock while showing a meaningful message to the user.

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

通用except块,用于处理未知异常 (Genericexceptblock 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 useexceptblocks to handle specific exception classes we should always have agenericexceptblock 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 firstexceptblock will handle theZeroDivisionError, secondexceptblock will handle theValueErrorand for any other exception that might occur we have the thirdexceptblock.

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

In the coming tutorials we will learn aboutfinallyblock and how to raise an exception using theraisekeyword.

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

翻译自: /python/exception-handling-python

python异常处理

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。