大家好,又见面了,我是你们的朋友全栈君。
抛出异常相当于是停止运行这个函数中的代码,将程序执行转到 except 语句。
如果没有 try 和 except 语句覆盖抛出异常的 raise 语句,该程序就会崩溃,并显示异常的出错信息。通常是调用该函数的代码知道如何处理异常,而不是该函数本身。所以你常常会看到 raise 语句在一个函数中,try 和 except 语句在调用该函数的代码中。
使用 try 和 except 语句,可以更优雅地处理错误,而不是让整个程序崩溃。
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception("Symbol must be a single character string.")
if width <= 2:
raise Exception("Width must be greater than 2.")
if height <= 2:
raise Exception("Height must be greater than 2.")
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
except Exception as err:
print('An exception happened: ' + str(err))
/usr/bin/python3.5 /home/strong/workspace/master.py
****
* *
* *
****
OOOOOOOOOOOOOOOOOOOO
O O
O O
O O
OOOOOOOOOOOOOOOOOOOO
An exception happened: Width must be greater than 2.
An exception happened: Symbol must be a single character string.
Process finished with exit code 0
https://yongqiang.blog.csdn.net/
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180616.html原文链接:https://javaforall.cn