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)

     

     

  • 相关阅读:
    FTPClient使用中的问题--获取当前工作目录为null
    MGR安装
    脚本在Shell可以执行成功,放到crontab里执行失败
    使用Python通过SMTP发送邮件
    MySQL Router
    事务管理(ACID)
    mysqldump使用
    MySQL InnoDB Cluster
    Linux LVM逻辑卷配置过程详解(创建、扩展、缩减、删除、卸载、快照创建)
    centos命令行控制电脑发出滴滴声
  • 原文地址:https://www.cnblogs.com/NancyRM/p/8038461.html
Copyright © 2011-2022 走看看