异常处理与模块
1、异常
"""
try:
正常程序执行此块代码
except:
抛出错误执行此代码块
"""
try:
num = int(input('请随便输入一个数然后转为整数类型:'))
# 字符串是不能直接转成int类型的
print(num)
except Exception as e: # Exception异常类的父类 ValueError
print(e) # 仅仅只是打印异常信息
# invalid literalfor int() with base 10: 'a'
print(e.__class__.__name__, ":", e) # 打印出当前异常对象的名字
# ValueError: invalid literalfor int() with base 10: 'a'
print(1) # 1
print(1) # 1
print(1) # 1
print(1) # 1
# noinspection PyBroadException
try:
# 正常程序时执行代码块
ipt = input("请输入:")
ipt = float(ipt)
print(ipt)
except Exception as e:
# 异常程序时执行代码块
ipt = 1
print(ipt)
"""
ValueError
NameError
IndexError
ZeroDivisionError
都继承Exception这个父类
"""
li = [1, 2, 3]
print(li[3]) # IndexError: list index out of range
print(1 / 0) # ZeroDivisionError: division by zero
"""try-except-else 有异常执行异常代码,没有异常则执行else代码"""
try:
li = [1, 2, 3, 4]
print(li[1]) # 2
# li[4] # 报错 我想把异常信息打印出来
# except IndexError as e: # e = IndexError
# print(e)
# print("hello")
except Exception as e:
# 类的对象实例调用__class__属性时会指向该实例对应的类,而后再调用 __name__ 就会输出该实例对应的类的类名
print(e.__class__.__name__, ":", e)
else:
print('没有异常!!!') # 没有异常!!!
"""try-except-finally 无论有无异常,都会执行finally代码"""
try:
li = [1, 2, 3, 4]
li[4] # 报错 我想把异常信息打印出来
except IndexError as e: # e = IndexError
print(e) # list index out of range
print("hello") # hello
except Exception as e:
# 类的对象实例调用__class__属性时会指向该实例对应的类,而后再调用 __name__ 就会输出该实例对应的类的类名
print(e.__class__.__name__, ":", e) # 打印当前异常对象的名字
else:
print('123')
finally:
print('我最棒!') # 我最棒!
2、主动抛出异常
"""
抢课 学校官网 卡住 网页崩溃了 请稍后再试 主动的抛出了一个异常
2w 2000并发
raise
"""
def test(level):
if level > 2000:
raise Exception("请稍后再试")
try:
test(20000)
except Exception as e:
print(e, 'system error!')
else:
print("success")
# 执行结果:请稍后再试 system error!
3、自定义异常
# 判断密码长度 如果密码长度小于6 主动触发异常 并抛出异常信息(打印提示)
class pwdlenERROR(Exception):
def __init__(self, length, min_length):
self.length = length
self.min_length = min_length
# 输出自定义的内容
def __str__(self):
return f"你输入的密码长度为{self.length},不能低于最小长度{self.min_length}"
def fun():
try:
password = input('请输入你的密码:')
if len(password) < 6:
raise pwdlenERROR(len(password), 6) # pwdlenERROR(len(password), 6) 创建了一个对象
except Exception as e:
print(e)
else:
print('密码长度符合要求')
fun()
# 运行代码,输入123,运行结果为:你输入的密码长度为3,不能低于最小长度6
4、模块
# import math # 内置模块 库 (内置库 第三方库(通过pip工具进行下的))
import math
# math.pi
# from math import pi
from math import * # 全部导入 # 将所有的math中的函数导入
# pi
# import numpy as np # 起一个别名 # 清洗数据
# import matplotlib as mp # 可视化界面展示的
# from selenium.webdriver.support.ui import WebDriverWait as WW # 自动化爬虫工具
"""time模块"""
import time
# print(1)
# time.sleep(3) # 暂停3秒
# print(5)
print(time.time()) # 1685875490.8150911 秒时间戳 从1970年的凌晨到现在
print(time.localtime()) # 本地的时间
# time.struct_time(tm_year=2023, tm_mon=6, tm_mday=4, tm_hour=18, tm_min=44, tm_sec=50, tm_wday=6, tm_yday=155, tm_isdst=0)
# tm_wday=6, 一周的第几天
# tm_yday=155,一年的第几日
# tm_isdst=0 夏令时
print(time.strftime("%Y-%m-%d %H:%M:%S")) # 2023-06-04 18:44:50
"""datetime模块"""
import datetime
print(datetime.datetime.now()) # 2023-06-04 18:44:50.817085
5、练习:
定义input_password函数,提示用户输入密码.
如果用户输入长度<8,主动抛出异常 提示(raise Exception("len too short!"))
如果用户输入长度>=8,返回输入的密码
class MyException(Exception):
def __init__(self, password):
self.password = password
def __str__(self):
return "len too short!"
def input_password():
try:
password = input("请输入密码:")
if len(password) < 8:
raise MyException(len(password))
except Exception as e:
print(e)
else:
print(f"你的密码是:{password}")
input_password()
运行结果: