异常
当Python无法正常处理程序时就会发生一个异常,会影响程序的正常执行。异常也是python对象,表示一个错误。
异常捕获
当python脚本有发生异常的可能时,就需要捕获异常,避免程序终止执行。
语法
try:
正常程序执行的代码块
except:
异常程序执行的代码块 #虽然不会报错终止程序,但无法记录下具体异常种类
try:
ipt = input('qingshuru')
i = int(ipt) #程序出错,i=1
print(i)
except: #异常程序执行的代码块
i = "错误"
print(i)
''' 细分错误的好处 1,方便修改 2,细分错误,一般是用于载入日志用的 '''
try:
li = [1, 2, 3, 4]
li[4]
# li['a'] # ValueError
except IndexError as e: #except 可以有多个
print("越界")
except Exception as e: # e = TypeError()
print(e)
try·except·else
~如果抛出异常执行except内部代码
~如果程序正常执行else内部代码
try:
li = [1, 2, 3, 4]
li[1]
# li['a'] # ValueError
except IndexError as e: #except 可以有多个
print("越界")
except Exception as e: # e = TypeError()
print(e)
else:
print("程序正常,运行内代码")
try·finally
不管程序有无发生异常,都将执行finally内部代码。
try:
li = [1, 2, 3, 4]
li[1]
# li['a'] # ValueError
except IndexError as e: #except 可以有多个
print("越界")
except Exception as e: # e = TypeError()
print(e)
else:
print("程序正常,运行内代码")
finally:
print('不管程序怎样,都执行')
else和finally不能有多个
主动触发异常
在实际开发中,在程序不满足某条件时,通常会主动抛出异常
语法小练习
当烹饪时间小于五时,则主动触发没有熟异常:否则熟了
def Test1(level):
if level < 5:
raise Exception("没有熟")
try:
i = int(input('已经烹饪的时间'))
Test1(i)
except Exception as e:
print(e)
else:
print("熟了,请吃")
finally:
print("用餐愉快")
自定义异常
当需要自定义满足一些规则时,就可以自定义异常。
自定义异常通过创建一个新的异常值,自定义名字与内容,并且需要继承Exception类实现。
小练习:密码长度不能低于6
class ShotInputError(Exception):
# 设置抛出异常
def __str__(self):
return f'你输入的密码不能低于六位数'
# 捕获错误
def main():
try:
num = input('请输入密码')
if len(num) < 6:
raise ShotInputError()
except Exception as result: # result = Exception()
print(result)
else:
print('密码输入完成')
main()
断言
'''
断言:assert 条件
条件成立就往下执行代码
条件不成立,直接抛出异常
'''
print('1'*30)
assert '2.0' == 2 #AssertionError,一般用于强制用户服从
print('1'*30)
补充:
# import demo # demo.test1() # from demo import test1 # from demo import * # test1() from demo import test1 as t1 def test1(): print('11') test1() t1() ''' as 相当于重名了 解决了命名冲突 精简了函数名 '''
模块
sys模块常用方法
sys是与python解释器交互模块
import sys
print(sys.argv) #list,第一个元素 当前文件的绝对路径,可以传入多个元素
# res = sys.argv[1] # win+r cmd 打开一个窗口
'''
1,win+r 输入cmd 打开一个窗口
2,切入盘符:当前文件的盘符
3,cd文件路径
4,python 文件.py 参数
'''
# if res == 'yes':
# print('是的')
print(sys.version)#解释器版本
print(sys.path)#模块搜索路径
sys.exit() #退出程序
# print('1')
os模块
print(os.getcwd()) # 打印当前工作目录
os.chdir('c:')#改变当前工作目录
print(os.getcwd())
os.makedirs('Logic20\\Basic') # 以递归的方式创建多个文件夹
os.removexattr('Logic20\\Basic') # 文件夹为空才能删除,删除多个
os.mkdir('Logic20')#只能创建单个文件夹
os.rmdir('Logic20')#只能删除单个文件夹
print(os.path.exists('Logic20'))#判断该路径下的文件或文件夹是否存在
dir_path = 'Logic\\Basic'
if not os.path.exists(dir_path):
os.makedirs(dir_path)
os.path.join()#拼接
j_path= os.path.join(os.getcwd(),'Logic20')
print(j_path)