- 难度级别: 简单
注意: 所有程序都在 python 版本 3 及更高版本上运行。
1)以下程序的输出是什么?
data = 50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Division successful ', end = '') try: data = data/5 except: print('Inside except block ', end = '') else: print('HY', end = '')
a) Cannot divide by 0 HY
b) Cannot divide by 0
c) Cannot divide by 0 Inside except block HY
d) Cannot divide by 0 Inside except block
答: (a)
说明: else 代码块只有在 try 块没有发生异常时才会执行。
2) 以下程序的输出是什么?
data = 50 try: data = data/10 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') finally: print('Haiyong ', end = '') else: print('Division successful ', end = '')
a) Runtime error
b) Cannot divide by 0 Haiyong
c) Haiyong Division successful
d) Haiyong
答: (a)
解释: python 中不允许 finally 块后面的 else 块。使用这种格式时,Python 会抛出语法错误。
3) 以下程序的输出是什么?
value = [1, 2, 3, 4] data = 0 try: data = value[4] except IndexError: print('HY', end = '') except: print('Haiyong ', end = '')
a) Haiyong
b) HY
c) HY Haiyong
d) 编译错误
答: (b)
解释: 一次只捕获一个异常,即使try 块中的throw 异常很可能属于多个异常类型。
4) 以下程序的输出是什么?
value = [1, 2, 3, 4] data = 0 try: data = value[3] except IndexError: print('HY IndexError ', end = '') except: print('Haiyong IndexError ', end = '') finally: print('Hai IndexError ', end = '') data = 10 try: data = data/0 except ZeroDivisionError: print('HY ZeroDivisionError ', end = '') finally: print('Hai ZeroDivisionError ')
a) HY ZeroDivisionError HY ZeroDivisionError
b) HY ZeroDivisionError Hai ZeroDivisionError
c) Hai IndexError HY ZeroDivisionError Hai ZeroDivisionError
d) Hai IndexError HY ZeroDivisionError
答: (c)
解释: 无论是否发生异常,finally 代码块总是被执行。如果发生异常,则先执行 except 块,然后执行 finally 块。
5) 以下程序的输出是什么?
value = [1, 2, 3, 4, 5] try: value = value[5]/0 except (IndexError, ZeroDivisionError): print('Haiyong ', end = '') else: print('HY', end = '') finally: print('Hai ', end = '')
a) Compilation error
b) Runtime error
c) Haiyong HY Hai
d) Haiyong Hai
答: (d)
解释: python 中定义了 try 之间的 finally 块之间的 else 块。如果 try 块中没有异常,则执行 else,然后执行 finally 块。可以定义一个except块来捕获多个异常。
如果大家发现任何不正确的地方,可以在下方评论区告诉我,互相学习,共同进步!