#如果try块引发NameError,则打印一条消息,如果是其他错误打印另一条 try: print(x) #print(x=1) except NameError: print("Variable is not defined") except: print("Something else went wrong") #如果没有引发错误,可以使用else关键字来定义要执行的代码块 try: print("hello") except: print("Something else went wrong") else: print("Nothing went wrong") #所有其它的错误类型都是Exception的子类,所以不知道会引发什么错误的情况下可以用Exception #finally: 无论会不会引发错误,最终都会执行的语句块 try: print(x) except Exception: print("Opps,有异常") finally: print("123") #例一: #试图打开并写入一个不可写的文件: try: f = open("test.txt") f.write("My name is vv") except: print("Something went wrong") finally: f.close() print("关闭文件") #引发(抛出)异常: raise #try...except 语句不会中止程序,raise语句引发异常并终止程序 # x = -1 # if x < 0: # raise Exception("Sorry,the num blew zero") x = "hello" if type(x) is not int: raise Exception("您输入的类型不正确")