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 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 = 10
    b = 0
    print("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 = 10
    b = 0
    print("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异常处理

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值