zoukankan      html  css  js  c++  java
  • 异常处理

    异常处理的基本格式

    try:
        int('123')
        raise Exception('阿萨大大是阿斯蒂') # 代码中主动抛出异常
    except Exception as e:
        print(e)
    try:
        v = []
        v[11111] # IndexError
    except ValueError as e:
        pass
    except IndexError as e:
        pass
    except Exception as e:
        print(e) # e是Exception类的对象,中有一个错误信息。
    View Code
    finally不管报不报错都会执行
    try:
        int('asdf')
    except Exception as e:
        print(e) # e是Exception类的对象,中有一个错误信息。
    finally:
        print('最后无论对错都会执行')
        
    # #################### 特殊情况 #########################
    def func():
        try:
            # v = 1
            # return 123
            int('asdf')
        except Exception as e:
            print(e) # e是Exception类的对象,中有一个错误信息。
            return 123
        finally:
            print('最后')
    
    func()
    View Code

    主动触发异常

    try:
        int('123')
        raise Exception('阿萨大大是阿斯蒂') # 代码中主动抛出异常
    except Exception as e:
        print(e)

    例子

    def func():
        result = True
        try:
            with open('x.log',mode='r',encoding='utf-8') as f:
                data = f.read()
            if 'alex' not in data:
                raise Exception()
        except Exception as e:
            result = False
        return result
    View Code
    自定义异常
    class MyException(Exception):
        pass
    
    try:
        raise MyException('asdf')
    except MyException as e:
        print(e)
    class MyException(Exception):
        def __init__(self,message):
            super().__init__()
            self.message = message
    
    try:
        raise MyException('asdf')
    except MyException as e:
        print(e.message)
    View Code
  • 相关阅读:
    将一张图片的人物融入另一张图片中
    填充---内容识别图片
    使用蒙版--渐变--制作瓶子倒影
    form表单基础知识
    表格排版及其表格嵌套
    HTML表格,table,thead,tbody,tfoot,th,tr,td,的属性以及跨行,跨列
    垃圾收集,内存问题
    JS预解析机制
    python ==》 内置函数
    python ==》 递归
  • 原文地址:https://www.cnblogs.com/biu-py/p/11221313.html
Copyright © 2011-2022 走看看