Python 异常处理

# 1 通常异常

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementClickInterceptedException, ElementNotVisibleException

driver = webdriver.Chrome()

try:
    # 尝试执行的代码
    pass
except NoSuchElementException:
    # 针对错误类型1,对应的代码处理
    pass
except TimeoutException:
    # 针对错误类型2,对应的代码处理
    pass
except(ElementClickInterceptedException, ElementNotVisibleException):
    # 针对错误类型3和4,对应的代码处理
    pass
except Exception as e:
    # 打印错误信息
    print(e)
else:
    # 如果try块中没有异常,对应的代码处理
    pass
finally:
    # 无论是否出现异常,都会执行的代码
    print('无论是否有异常,都会执行的代码')
# 2 抛出异常:使用 raise 关键字来抛出异常

def divide(a, b):
    if b == 0:
        raise Exception("除数不能为零")
    return a / b


try:
    divide(3, 0)
except Exception as e:
    print(e)
# 3 自定义异常类: 自定义异常类需要继承自 Exception 类。
class CustomError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg


def add(a, b):
    if a < 0 or b < 0:
        raise CustomError("自定义的异常")
    return a + b
'''
参考:
【python】异常处理
https://blog.csdn.net/w3360701048/article/details/137504337
2024年Python最全python异常(概念、捕获、传递、抛出)_异常python(2)
https://blog.csdn.net/2401_84584796/article/details/138355865
Python异常处理:三种不同方法的探索与最佳实践
https://blog.csdn.net/weixin_45081575/article/details/134356343
Selenium异常集锦
https://www.cnblogs.com/FunTester/p/13844892.html
'''

相关推荐

  1. Python异常处理

    2024-07-22 05:18:01       30 阅读
  2. python--异常处理

    2024-07-22 05:18:01       38 阅读
  3. Python爬虫--异常处理

    2024-07-22 05:18:01       23 阅读
  4. Python异常处理

    2024-07-22 05:18:01       29 阅读
  5. Python异常处理

    2024-07-22 05:18:01       26 阅读
  6. python 异常处理、随机数、

    2024-07-22 05:18:01       26 阅读
  7. Python异常处理

    2024-07-22 05:18:01       13 阅读
  8. Python 异常处理

    2024-07-22 05:18:01       14 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 05:18:01       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 05:18:01       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 05:18:01       45 阅读
  4. Python语言-面向对象

    2024-07-22 05:18:01       55 阅读

热门阅读

  1. Python中的__new__方法及实现单例模式

    2024-07-22 05:18:01       14 阅读
  2. FlowUs横向对比几款笔记应用的优势所在

    2024-07-22 05:18:01       16 阅读
  3. 公式推导类

    2024-07-22 05:18:01       16 阅读
  4. 【C++】C++内存泄漏介绍及解决方案

    2024-07-22 05:18:01       15 阅读
  5. 后台接口的配置

    2024-07-22 05:18:01       15 阅读
  6. Optional 中 map 和 flatMap 区别是啥?

    2024-07-22 05:18:01       14 阅读
  7. 实习手计(4):月末碎碎念!

    2024-07-22 05:18:01       12 阅读
  8. Nginx详细配置(最佳实践)

    2024-07-22 05:18:01       16 阅读
  9. 信息系统安全保护等级调整的流程

    2024-07-22 05:18:01       15 阅读
  10. Netty SSL/TLS

    2024-07-22 05:18:01       19 阅读
  11. C语言排序算法

    2024-07-22 05:18:01       12 阅读
  12. 如何使用Python进行数据分析

    2024-07-22 05:18:01       17 阅读