异常:当程序运行出错时,它都会创建一个异常对象。如果我们编写了处理该异常的代码,程序将继续运行;如果我们未对程序进行异常处理,程序将停止,并显示tracback,其中包含有关异常的报告。
如何处理:try-except,try语句后面是程序所要执行的操作,而except则是针对程序运行可能出现的错误,告诉程序该怎么办。
若希望出现错误时直接跳过,不说明怎么错的,则编写为except : pass
示例1:ZeroDivisionError
def main(): first_number = input("first number: ") second_number = input("second number: ") try: answer = int(first_number)/int(second_number) except ZeroDivisionError: print("you can't divide by zero") else: print(answer) if __name__ == '__main__': main()
示例2:FileNotFoundError
def file_notfound(): try: with open('1.txt','r') as f: temp = f.read() except FileNotFoundError: print("sorry,the file does not exist.") if __name__ == '__main__': file_notfound()