zoukankan      html  css  js  c++  java
  • Python3.x基础学习-异常报错处理

    异常处理

    异常就是语法正常的前提下,程序运行时报错就是异常
    当python脚本发生异常时我们需要捕获处理它,否则程序会终止执行

    print('hello world')
    print(1/0)        # ZeroDivisionError: division by zero
    print('代码结束')
    异常处理 try,except,else,finally,raise
    程序从上到下执行,先执行try的代码,如果代码报错,则不会执行下面的代码
    执行except中的异常代码
    如果try没报错,则不执行except中代码

    try:
        print('hello word')
        print(1/0)
    except IndexError:
        print('索引异常')
    
    except ZeroDivisionError:
        print('o是除数异常')
    
    except:
        print("代码有错误")
    print('最后的代码')

    常见的报错信息:

    ZeroDivisionError,IndexError,NameError,FileNotFoundError,FileExistsError,TypeError

    try正常执行结束,不会走except,走else
    try中有错误,走except,不走else
    无论代码有无异常,都会走finally

    
    
    try:
        print("abc")
        print(1/0)
        print('b')
    except BaseException:
        print("出现错误了")
    else:
        print("没有异常")
    finally:
        print("有无异常都得给我跑起来")
    
    

    内层try无法捕获异常,会向外传递
    外层异常无法捕获,会继续向外传递,知道捕获异常为止,没捕获报错

    try:
        with open('test2.py','w+') as f:
            content = f.read()
            try:
                with open('test3.txt','r') as f:
                    print(f.read())
            except FileExistsError:
                print("文件未发现错误")
    except BaseException:
        print('外层捕获')

    变量名也可以作为异常的对象,一般使用e来表示
    e对象中包含了异常信息的一些描述,我们可以根据描述做不同的处理

    try:
        print("hello world")
        print(1/0)
        print("over")
    except Exception as e:
        print(e)
    
    
    def func1():
        print("--func1-1-")
        print(num)
        print('---func1-2-')
    
    def func2():
        try:
            print('---func2--1')
            func1()
            print('----func2--2')
        except FileNotFoundError:
            print("func1出现异常")
        else:
            print('----func2--3')
        finally:
            print("最后的代码")
    
    try:
        func2()
        print('func2执行完了')
    except NameError:
        print("命名错误")
    
    


    用户可以根据业务逻辑手动抛出异常
    并且用户可以根据需求来抛出系统异常(python 已经定义好的异常)和用户自定义异常

    try:
        name = a
        if name.isalpha():
            raise Exception('不能全是字母')
    except BaseException as e:
        print("----exception----",e)
    
    
    class ShortInputException(Exception):
        pass
    
    try:
        raise ShortInputException('输入太短')
    except BaseException as e:
        print(e)
    
    # 判断输入的字符串长度,如果小于指定长度就报错
    class MyException(Exception):
        def __init__(self,length,atleast):
            self.length = length #输入的字符串长度
            self.atleast = atleast
        def __str__(self):
            return '长度{},规定长度{}'.format(self.length,self.atleast)
    
    try:
        msg = input("请输入:")
        if len(msg)<5:
            raise MyException(len(msg),5)
    except Exception as e:
        print(e)



  • 相关阅读:
    imagemagick-图片
    selenium-嘿
    centos命令行连接无线网络
    centos7安装桌面合盖不休眠
    mysql执行命令:ERROR 1820 (HY000): You must reset your password
    编码规范 C++
    Docker使用总结
    JAVA使用总结
    VS IDE 相关
    编程网站总结
  • 原文地址:https://www.cnblogs.com/johnsonbug/p/12709995.html
Copyright © 2011-2022 走看看