Python基础学习(六)

文章目录

异常

初探异常

什么是异常与异常处理

  • 异常就是错误
  • 异常会导致程序崩溃并停止运行
  • 能监控并捕获异常,将异常部位的程序进行修理使得程序继续正常运行

异常语法

异常示例


python 复制代码
def upper(str_data):
    new_str = ''
    try:
        new_str = str_data.upper()
    except:
        print('程序异常')
    return new_str

result = upper(1) #程序异常
print(result) # ''

捕获通用异常

  • 无法确定是哪种异常的情况下使用的捕获方法
python 复制代码
def upper(str_data):
    new_str = ''
    try:
        new_str = str_data.upper()
    except Exception as e:
        print('程序异常', e) #程序异常 'int' object has no attribute 'upper'
    return new_str

result = upper(1) 
print(result)

捕获具体的异常

  • 确定是哪种异常的情况下使用的捕获方法
  • except <具体异常类型> as e

捕获多个异常

  • 当有多个except代码块有多个的时候,当捕获到第一个后,不会继续往下捕获

异常类型

异常类型集合


异常中的finally

finally的功能

  • 无论是否发生异常,一定会执行的代码块
  • 在函数中,即便在try或者except中进行了return ,也依然会执行finally中的语法块
  • try语法至少要伴随except或者finally中的一个

finally的用法

python 复制代码
def test1():
    try:
        1/0
    except Exception as e:
        print(e) # division by zero
    finally:
        return 'finally'

if __name__ == '__main__':
    print(test1()) # finally

自定义异常与主动抛出异常

自定义抛出异常--raise

将信息以报错的形式抛出(类似Java中的 throw )

python 复制代码
def test():
   raise ValueError('自定义异常')

test()

#结果
Traceback (most recent call last):
 File "D:\project\python_protice\py基础\muke\自定义异常.py", line 6, in <module>
   test()
   ~~~~^^
 File "D:\project\python_protice\py基础\muke\自定义异常.py", line 4, in test
   raise ValueError('自定义异常')
ValueError: 自定义异常
python 复制代码
# coding:utf-8

def test():
    raise ValueError('自定义异常')

print('--------------------------')

def test2():
    try:
        test()
    except Exception as e:
        print(e) # 自定义异常
    finally:
        return 'finally'

print(test2()) # finally

自定义异常类

  • 继承基类Exception
  • 在构造函数中定义错误信息
python 复制代码
class NewError(Exception):
    def __init__(self, message):
        self.message = message

def test3():
    raise NewError('自定义的一个异常类')
print(test3())

#结果
Traceback (most recent call last):
  File "D:\project\python_protice\py基础\muke\自定义异常.py", line 31, in <module>
    print(test3())
          ~~~~~^^
  File "D:\project\python_protice\py基础\muke\自定义异常.py", line 30, in test3
    raise NewError('自定义的一个异常类')
NewError: 自定义的一个异常类

断言

断言的功能 -- assert

用于判断一个表达式,在表达式条件为false的时候触发异常

python 复制代码
assert 1>2,'1不大于2'
#结果
Traceback (most recent call last):
  File "D:\project\python_protice\py基础\muke\assert断言.py", line 3, in <module>
    assert 1>2,'1不大于2'
           ^^^
AssertionError: 1不大于2
相关推荐
花酒锄作田14 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪18 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽19 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战19 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama