千慧 2020-04-11
s1 = input("请输入一个字符:") try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e)
s1 = input("请输入一个字符:") try: int(s1) except Exception as e: print(e)
try: pass # 主代码块 except KeyError as e: pass # 出现该异常时执行 else: pass # 主代码块执行完,执行该块(若捕获到异常,则不执行该句) finally: pass # 无论异常与否,最终执行该块(不论try、except、else是否出现异常,该句都会执行)
s1 = input("请输入一个字符:") try: if len(s1) != 1: raise Exception(KeyError) # 抛出KeyError异常 except Exception as e: # 捕获异常 print(e)
class MyException(Exception): def __init__(self, code, msg): self.error_code = code self.error_msg = msg def __str__(self): return self.error_code, self.error_msg try: raise MyException(3000, ‘自定义异常‘) except MyException as e: print(e.error_code, e.error_msg)