Python try-finally 块
可以在 try 块之后使用一个 finally 块。在 finally 块中可以放置任何必须执行的代码,无论 try 块是否引发异常。
try-finally 语句的语法如下:
try: You do your operations here; ...................... Due to any exception, this may be skipped. finally: This would always be executed. ......................
注意 − 您可以提供except子句,或finally子句,但不能同时使用。您也不能与finally子句同时使用else子句。
示例
try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") finally: print ("Error: can\'t find file or read data") fh.close()
如果您没有以写入模式打开文件的权限,则会产生以下输出。
Error: can't find file or read data
相同的示例可以更清晰地编写如下 –
try: fh = open("testfile", "w") try: fh.write("This is my test file for exception handling!!") finally: print ("Going to close the file") fh.close() except IOError: print ("Error: can\'t find file or read data")
当try块中抛出异常时,执行立即转到 finally 块。在执行 finally 块的所有语句之后,异常被重新引发,并在try-except语句的下一个更高层的except语句中处理(如果有的话)。
带参数的异常
异常可以具有参数,这是一个提供有关问题的附加信息的值。参数的内容因异常而异。您可以通过在except子句中提供一个变量来捕获异常的参数,如下所示−
try: You do your operations here ...................... except ExceptionType as Argument: You can print value of Argument here...
如果你写的代码处理一个异常,可以在except语句中跟随异常名称后面有一个变量。如果你要捕获多个异常,可以在异常的元组后面有一个变量。
这个变量接收异常的值,通常包含异常的原因。这个变量可以接收单个值或者多个值的元组形式。这个元组通常包含错误字符串、错误号码和错误位置。
示例
以下是一个处理单个异常的示例 –
# Define a function here. def temp_convert(var): try: return int(var) except ValueError as Argument: print("The argument does not contain numbers\n",Argument) # Call above function here. temp_convert("xyz")
它将产生以下 输出 −
The argument does not contain numbers invalid literal for int() with base 10: 'xyz'
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com