1. 如何利用raise抛出你定义的异常?
raise Exception(‘This is the error message.’)
(‘ ’)里是传递给exception函数的字符串,包含有用的出错信息。
>>> raise Exception('U R wrong.')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
raise Exception('U R wrong.')
Exception: U R wrong.
>>>
>>> def boxPrint(symbol,width,height):
if len(symbol)!=1:
raise Exception('只能是单一字符')
if width<=2:
raise Exception('宽度必须大于2')
if height<=2:
raise Exception('高度必须大于2')
print(symbol*width)
for i in range(height-2):
print(symbol+(' '*(width-2))+symbol)
print(symbol*width)
>>> boxPrint('$',8,8)
$$$$$$$$
$ $
$ $
$ $
$ $
$ $
$ $
$$$$$$$$
>>> boxPrint('$',1,12)
Traceback (most recent call last):
File "<pyshell#22>", line 1, in