zoukankan      html  css  js  c++  java
  • Python异常

    什么是异常

    异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。 一般情况下,在Python无法正常处理程序时就会发生一个异常。 异常是Python对象,表示一个错误。 当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。

    常见异常类型

    异常名称 描述
    FileNotFoundError 找不到指定文件的异常
    NameError 未声明/初始化对象(没有属性)
    BaseException 所有异常的基类

    异常处理语句

    • try...except...
    • try...except...finally
    • raise

     

    1、try...except

    FileNotFoundError

    #找不到指定文件的异常
     try:
         fileName=input("Please input the filename:")
         open("%r.txt" %fileName)
     except FileNotFoundError:
         print("File not found!")

    NameError

    #未声明/初始化对象(没有属性)
     try:
         print(stu)
     except NameError:
         print("变量未定义")

    BaseException

     try:
         print(stu)
     except BaseException:
         print("变量未定义")

    try...except...as

     try:
    #     stu='Nancy'
         print(stu)
     except BaseException as msg:
         print(msg)

    try...except...else使用

     try:
    #     stu='Nancy'
         print(stu)
     except BaseException as msg:
         print(msg)
     else:
         print("stu is defined!")

    2、try...except...finally输出

     try:
         stu='Nancy'
         print(stu)
     except BaseException as msg:
         print(msg)
     else:
         print("stu is defined!")
     finally:
         print("The end!")

    3、raise抛出异常

    前面try语句是执行过程中捕获代码块的异常,而raise是通过事先定义一个条件,一旦符合异常条件就抛出异常。

    def division(x,y):
        if y==0:
         raise ZeroDivisionError("Zero is not allowed!")
        else:
            return x/y
    try:
        division(8,0)
    except BaseException as msg:
        print(msg)

     

     

  • 相关阅读:
    本地代码库关联Github
    常用正则表达式
    IDEA开启并配置services窗口
    数据结构总结
    IDEA导入项目后文件出现时钟的原因及解决方案
    win7硬盘安装过程图解(需要编辑)
    How to Create a Automated Task that Runs at a Set Time in Windows 7
    【转】Code Review(代码复查)
    (收藏)C#开源资源大汇总
    Windows Workflow Foundation:向跟踪服务(TrackingService)传递数据
  • 原文地址:https://www.cnblogs.com/NancyRM/p/8038461.html
Copyright © 2011-2022 走看看