python try异常处理 (2)

异常捕捉可以使用 try/except 语句。

try: num = int(input("Please enter a number: ")) print(num) except: print("You have not entered a number, please try again!") PS D:\learning\git\work> python test.py Please enter a number: 60 60 PS D:\learning\git\work> python test.py Please enter a number: d You have not entered a number, please try again! PS D:\learning\git\work>

try 语句执行顺序如下:

首先,执行 try 代码块。

如果没有异常发生,忽略 except 代码块,try 代码块执行后结束。

如果在执行 try 的过程中发生了异常,那么 try 子句余下的部分将被忽略。

如果异常的类型和 except 之后的名称相符,那么对应的 except 子句将被执行。

一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。

try/except...else

如果使用这个子句,那么必须放在所有的 except 子句之后。
else 子句将在 try 代码块没有发生任何异常的时候被执行。

try: test_file = open("testfile.txt", "w") test_file.write("This is a test file!!!") except IOError: print("Error: File not found or read failed") else: print("The content was written to the file successfully") test_file.close() PS D:\learning\git\work> python test.py The content was written to the file successfully PS D:\learning\git\work>

如果写入没有问题,就会走到 else 提示成功。

try-finally

无论是否异常,都会执行最后 finally 代码。

try: test_file = open("testfile.txt", "w") test_file.write("This is a test file!!!") except IOError: print("Error: File not found or read failed") else: print("The content was written to the file successfully") test_file.close() finally: print("test") PS D:\learning\git\work> python test.py The content was written to the file successfully test raise

使用 raise 抛出一个指定的异常

def numb( num ): if num < 1: raise Exception("Invalid level!") # 触发异常后,后面的代码就不会再执行 try: numb(0) # 触发异常 except Exception as err: print(1,err) else: print(2) PS D:\learning\git\work> python test.py 1 Invalid level! PS D:\learning\git\work>

语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。
最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。

参考链接:
https://www.runoob.com/python3/python3-errors-execptions.html
https://www.runoob.com/python/python-exceptions.html

---- 钢铁 648403020@qq.com 02.08.2021

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zydgjw.html