语法错误和异常 异常:程序运行的时候报出来的,xxxError 异常处理格式: try: 可能出现异常的代码 except: 如果有异常执行的代码 finally: 无论是否存在异常都会被执行的代码 情况一: try: 有可能产生多个异常 except 异常类型1: print() except 异常类型2: print() 注意:如果是多个except,异常类型的顺序许哟啊注意,最大的Exception要放在后面 情况二:获取Exception的错误原因 except Exception as err: print('Error',err)------》就是错误原因 [Error pop from empty list] def func(): try: a=int(input('请输入一个数字:')) b=int(input('请输入一个数字:')) f=input('请输入一个符号(+ - * /):') if f=='+': result=a+b elif f=='-': result=a-b elif f=='*': result=a*b elif f=='/': result=a/b else: print('输入的符号不正确') print(result) list=[] list.pop() with open(r'F:\mm','r')as rstream: container=rstream.read() print(container) except ZeroDivisionError: print('除数不可以为0') except ValueError: print('请输入数字') except Exception as err: print('Error',err) func() 情况三: try: 有可能有异常的代码 except 类型1: pass else: 如果try中没有异常则进入的代码 注意:如果使用else则在try代码中不能出现return 情况四: 文件操作:fp=open() fp.read() fp.close() 数据库操作:close() try: pass except: pass finally: 无论是否异常都需要执行的代码 def func(): rstream=None try: with open('book', encoding='utf-8')as rstream: print(rstream.read()) return 1 # rstream = open(r'F:\p\ww\book.txt', 'rb', encoding='UTF-8') except Exception as err: print(err) return 2 finally: print('enter---------') if rstream: rstream.close() return 3 x=func() print(x) ''' 抛出异常 raise 注册: 用户名必须是6位 ''' def register(): username=input('输入用户名:') if len(username)<6 or len(username)>6: raise Exception('用户长度必须是6位') else: print('您的用户名是:{}'.format(username)) try: register() except Exception as err: print(err) else: print('chenggong ')
python笔记整理
最新推荐文章于 2024-05-01 22:18:49 发布