当前位置: 首页 > article >正文

【python】4_异常

目录

一、异常处理

1、异常捕获

基本捕获语法:

捕获指定异常:

 捕获多个异常:

捕获所有异常:

异常else & finally:

 2、异常的传递性

 二、模块

模块的导入方式

1、语法

 2、as 定义别名


一、异常处理

1、异常捕获

基本捕获语法:

try:

        可能发生错误的代码

except:

        如果出现异常执行的代码

捕获指定异常:

try:

        print(name)

except  NameError  as  e:

        print("name变量名未定义错误")

代码示例 

try:
    print(name)
except NameError as e: # e为别名,可任意定义
    print("name变量名未定义错误") # name变量名未定义错误
    print(e) # name 'name' is not defined

 捕获多个异常:

try:

        print(name)

except  (xxError,xxError)  as  e:  # 使用元组方式

        print("name变量名未定义错误")

 代码示例 

try:
    # print(name)
    print(1/0) # division by zero
except  (NameError ,ZeroDivisionError) as e:
    print(e)

捕获所有异常:

try:

        异常

except  Exception  as  e:  #  or   except:

        print(e)

 代码示例

try:
    print(1/0)
    # print(name)
except Exception as e:
    print(e)

异常else & finally:

try:

        可能发生错误的代码

except:

        如果出现异常执行的代码

else:

        没有异常时执行的代码

finally:

        有没有异常都会执行的代码

代码示例

try:
    f = open("E:/123.txt" , "r" , encoding="utf-8")
except Exception as e:
    print(e) # [Errno 2] No such file or directory: 'E:/123.txt'
    f = open("E:/123.txt", "w", encoding="utf-8")
else:
    print("123")
finally:
    f.close()

 2、异常的传递性

代码示例

def fun1():
    print("fun1开始")
    print(1 / 0)
    print("fun1结束")

def fun2():
    print("fun2开始")
    fun1()
    print("fun2结束")

def main():
    print("main开始")
    try:
        fun2()
    except Exception as e:
        print(e)
    print("main结束")

main()

 二、模块

模块的导入方式

1、语法

[ from 模块名]  import  [模块 |  类  |  变量  |  函数  |  *  ]    [ as  别名]

 代码示例--导入time模块

import time   # python内置的time模块
time.sleep(3)   # 延迟3秒
print("hello")

  代码示例--导入time模块中的sleep功能

from time import sleep  # 导入time模块的sleep功能
sleep(3)
print("hello")

 代码示例--导入time模块中全部的功能

from time import *  # 导入time模块的全部功能
sleep(3)
print("hello")
 2、as 定义别名

代码示例

from time import sleep as Sl # 给sleep定义别名
Sl(3)
print("hello")

http://www.kler.cn/a/551970.html

相关文章:

  • [LeetCode力扣hot100]-链表
  • 扩散模型中的马尔可夫链设计演进:从DDPM到Stable Diffusion全解析
  • labelimg的xml文件转labelme的json文件
  • Android ListPreference使用
  • 图床 PicGo+GitHub+Typora的下载安装与使用
  • 基于 Spring Cloud + Sentinel 的全面流量治理方案
  • fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
  • 《DeepSeek 一站式工作生活 AI 助手》
  • 提升接口性能之缓存
  • Spring Boot项目的基本设计步骤和相关要点介绍
  • Win10环境使用零讯ZeroNews内网穿透实现Deepseek对外服务
  • UDP
  • 全平台搭载旭日5!科沃斯GOAT智能割草机器人全新系列正式开售
  • 轻松搭建本地大语言模型(一)Ollama安装与使用
  • 山石网科×阿里云通义灵码,开启研发“AI智造”新时代
  • 记一次Ngnix配置
  • 智能合约与区块链中的NLP应用:自动化法律文书分析与合同审查【附核心实战代码】
  • 【UE5 C++课程系列笔记】30——自动拷贝DLL及其他资源
  • vue3-03初学vue3中的配置项setup(Composition API (组合API组件中所用到的:数据、方法等,均要配置在setup中)
  • 大模型基础知识快问快答