1、异常处理
try: print(num) except NameError as error: print("------NameError-------") print(error) except FileNotFoundError: print("------FileNotFoundError-------") except Exception as error: print("------Exception-------") print(error) else: print("没有异常时执行") finally: print("无论是否异常都执行") print("------running-------")
2、自定义异常
class ShortInputException(Exception): '''自定义的异常类''' def __init__(self, length, atleast): self.length = length self.atleast = atleast def test_error(): try: s = input("请输入-> ") if len(s) < 3: # raise引发一个自己定义的异常 raise ShortInputException(len(s), 3) except ShortInputException as error: print("ShortInputException:输入的长度是%d,长度至少应是%d" \ %(error.length, error.atleast)) else: print("没有异常") test_error()