小墨の博客

梦想需要付诸行动,否则只能是梦

Python 中的 try except else finally 异常处理(英文翻译)

Python Try Except

Python中的错误可以有两种类型,即语法错误和异常。错误是程序中出现的问题,由于这些问题,程序将停止执行。另一方面,当发生一些内部事件改变程序的正常流程时,会引发异常。

Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.

注意:有关更多信息,请参阅Python中的错误和异常

Note: For more information, refer to Errors and Exceptions in Python

常见的异常错误有:

Some of the common Exception Errors are : 

  • IOError: 文件无法打开 if the file can't be opened

  • KeyboardInterrupt: 当用户按下一个不必要的键时 when an unrequired key is pressed by the user

  • ValueError: 内置函数接收到错误的参数 when built-in function receives a wrong argument

  • EOFError: 在没有读取任何数据的情况下命中文件末尾 if End-Of-File is hit without reading any data

  • ImportError: 如果无法找到该模块 if it is unable to find the module


Python 中的 Try Except

Try Except in Python


在Python代码中,Try和Except语句用于处理这些错误。try块用于检查一些代码是否有错误,即当程序中没有错误时,try块内的代码将执行。而except块中的代码只要在前面的try块中遇到错误就会执行。

Try and Except statement is used to handle these errors within our code in Python. The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block.


语法:

Syntax: 

try:
    # 一些代码
    # Some Code
except:
    # 当 try 中发生错误时执行
    # Executed if error in the
    # try block

 

try() 是如何工作的?

How try() works?

  • 首先,执行try子句,即tryexcept子句之间的代码。

    First, the try clause is executed i.e. the code between try and except clause.

  • 如果没有异常,那么只有try子句会运行,除非该子句已经完成。

    If there is no exception, then only the try clause will run, except the clause is finished.

  • 如果发生异常,try子句将被跳过,except子句将运行。

    If any exception occurs, the try clause will be skipped and except clause will run.

  • 如果发生了任何异常,但代码中的except子句没有处理它,它会传递给外部的try语句。如果不处理异常,则停止执行。

    If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.

  • try语句可以包含多个except子句。

    A try statement can have more than one except clause.


代码1:没有异常,所以try子句会运行。

Code 1: No exception, so the try clause will run. 

# 用Python代码演示 try() 的工作原理
# Python code to illustrate
# working of try()
def divide(x, y):
    try:
        # 向下取整除(地板除): 只给出小数部分的答案
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")

# 查看参数并注意程序的工作
# Look at parameters and note the working of Program
divide(3, 2)

辅助空间: O(1)

Auxiliary Space: O(1)

输出:

Output : 

Yeah ! Your answer is : 1

代码1:有异常,所以只有except子句会运行。

Code 1: There is an exception so only except clause will run. 

# divide(x, y) 定义同上

# 查看参数并注意程序的工作
# Look at parameters and note the working of Program
divide(3, 0)

输出:

Output : 

Sorry ! You are dividing by zero

 

Else 语句

Else Clause

在python中,还可以在try-except代码块中使用else子句,它必须位于所有except子句之后。只有在try子句不引发异常时,代码才会进入else代码块。

In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code enters the else block only if the try clause does not raise an exception.

 

语法:

Syntax:

try:
    # 一些代码
    # Some Code
except:
    # 当 try 中发生错误时执行
    # Executed if error in the
    # try block
else:
    # 没有异常时执行
    # execute if no exception

代码:

Code:

# 用 try-except 描述 else 子句的程序
# Program to depict else clause with try-except

# 返回 a/b 的函数
# Function which returns a/b
def AbyB(a , b):
    try:
        c = ((a+b) // (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)

# 驱动程序来测试上述函数
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

输出:

Output:

-5.0
a/b result in 0

 


Python中的Finally关键字

Finally Keyword in Python

Python提供了关键字finally,它总是在try和except代码块之后执行。最后一个块总是在try块正常终止之后执行,或者在try块由于某些异常终止之后执行。

Python provides a keyword finally, which is always executed after the try and except blocks. The final block always executes after normal termination of try block or after try block terminates due to some exceptions.

 

语法:

Syntax:

try:
    # 一些代码
    # Some Code
except:
    # 当 try 中发生错误时执行
    # Executed if error in the
    # try block
else:
    # 没有异常时执行
    # execute if no exception
finally:
    # 一些代码.....(总是执行)
    # Some code .....(always executed)

代码:

Code:

# 演示 finally 的 Python 程序
# Python program to demonstrate finally

# 没有异常在 try 中抛出异常
# No exception Exception raised in try block
try:
    k = 5//0 # 抛出除零异常 raises divide by zero exception.
    print(k)

# 处理除零异常
# handles zerodivision exception    
except ZeroDivisionError:   
    print("Can't divide by zero")

finally:
    # 无论异常生成如何
    # 这个代码块都会被执行
    # this block is always executed 
    # regardless of exception generation.
    print('This is always executed')

输出:

Output:

Can't divide by zero
This is always executed

 

本文由程序员小墨翻译,英文原文:

Python Try Except: https://www.geeksforgeeks.org/python-try-except/


张小弟之家

本文链接:
文章标题:

本站文章除注明转载/出处外,均为原创,若要转载请务必注明出处。转载后请将转载链接通过邮件告知我站,谢谢合作。本站邮箱:admin@only4.work

尊重他人劳动成果,共创和谐网络环境。点击版权声明查看本站相关条款。

    • 评论列表:
    •  2291200076
       发布于 2023-01-16 20:41:06  回复该评论
    • 也可以通过 raise Exception('error info') 手动抛出一个异常

    发表评论:

    搜索
    本文二维码
    标签列表
    站点信息
    • 文章总数:508
    • 页面总数:20
    • 分类总数:92
    • 标签总数:208
    • 评论总数:61
    • 浏览总数:225323

    | | |
    | |  Z-Blog PHP