网络编程
位置:首页>> 网络编程>> Python编程>> Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用

作者:cinderamanda  发布时间:2022-10-18 14:31:45 

标签:Python,try-finally,try-except-else,try-except

try-except

作用:处理异常情况

用法:try:后面写正常运行的代码,except + 异常情况:后面写对异常情况的处理

示例:


try:
   num = int(input("Please input a number:\n"))
   print(42 / num)
except ZeroDivisionError: #except后为错误类型
   print("Divided by zero!")
except ValueError: #可以有多个错误类型
   print("Wrong value!")

运行结果:

Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用

注意:调用try语句时,try后的所有错误都将被捕捉,一旦遇到错误,立即跳到except语句块,错误之后的语句不再执行


def division(DivideBy):
       return 42 / DivideBy
try:
   print(division(1))
   print(division(0))
   print(division(7))
except ZeroDivisionError:#except后写错误类型
       print("Divided by zero!")

运行结果:

Python try-except-else-finally的具体使用 

try-except-else

和try-except类似,不过如果程序没有错误,也就是没有跳到except语句块,则执行else语句块,如果程序发生错误,即跳到except语句块,则直接跳过else语句块

示例程序:


def division(DivideBy):
       return 42 / DivideBy
try:
   num = int(input("Please input a integer:\n"))
   print(division(num))
except ZeroDivisionError:#except后写错误类型
       print("Divided by zero!")
except ValueError:
   print("Wrong input!")
else:
   print("No error. Good job!")

运行结果:

Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用 

try-finally

finally:无论try后是否有异常,都要执行


def division(DivideBy):
   return 42 / DivideBy
try:
   num = int(input("Please input a integer:\n"))
   print(division(num))
except ZeroDivisionError:  # except后写错误类型
   print("Divided by zero!")
except ValueError:
   print("Wrong input!")
else:
   print("No error. Good job!")
finally:
   print("Finished")

运行结果:

Python try-except-else-finally的具体使用

Python try-except-else-finally的具体使用

来源:https://blog.csdn.net/cinderamanda/article/details/119989374

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com