Python-抛出异常(try-except-else-finally)
try-except:
1 try: 2 a = int(input('输入被除数:')) 3 b = int(input('输入除数:')) 4 print('a / b = ', a/b) 5 except: 6 print('输入不合法') 7 print('程序结束')
1 try: 2 a = int(input('输入被除数:')) 3 b = int(input('输入除数:')) 4 print('a / b = ', a/b) 5 except ZeroDivisionError: 6 print('除数不能为0') 7 except ValueError: 8 print('只能输入数字串') 9 print('程序结束')
try-except-else:
1 try: 2 a = int(input('输入被除数:')) 3 b = int(input('输入除数:')) 4 result = a / b 5 except BaseException as e: 6 print('程序运行出错,', e) 7 else: 8 print('a / b = ', result) 9 print('程序结束')
try-except-else-finally:
1 try: 2 a = int(input('输入被除数:')) 3 b = int(input('输入除数:')) 4 result = a / b 5 except BaseException as e: 6 print('程序运行出错,', e) 7 else: 8 print('a / b = ', result) 9 finally: 10 print('谢谢使用') 11 print('程序结束')