Python|Python try-except-else-finally的具体使用
目录
- try-except
- try-except-else
- try-finally
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!")
运行结果:
文章图片
文章图片
文章图片
注意:调用try语句时,try后的所有错误都将被捕捉,一旦遇到错误,立即跳到except语句块,错误之后的语句不再执行
def division(DivideBy):return 42 / DivideBytry:print(division(1))print(division(0))print(division(7))except ZeroDivisionError:#except后写错误类型print("Divided by zero!")
运行结果:
文章图片
try-except-else 和try-except类似,不过如果程序没有错误,也就是没有跳到except语句块,则执行else语句块,如果程序发生错误,即跳到except语句块,则直接跳过else语句块
示例程序:
def division(DivideBy):return 42 / DivideBytry: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!")
运行结果:
文章图片
文章图片
文章图片
try-finally 【Python|Python try-except-else-finally的具体使用】
finally:
无论try后是否有异常,都要执行def division(DivideBy):return 42 / DivideBytry: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 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)
- Python|Python 9.20