Python3学习七之异常处理
来源:互联网 发布:汽车驾驶模拟器软件 编辑:程序博客网 时间:2024/06/03 21:38
Python3学习七之异常处理类似于java的try...catch
基本语法
try: block1except Error: block2
- except可以处理多个异常,将多个异常放入()内并使用,隔开就行了
- except中可以打印错误信息,将Error用关键字as命名err即可调用print
- try中还可以加入另一个子句finally,无论try是否发生异常finally的语句都会执行
- try...except后面可以跟else语句,其中当try中没有任何报错的情况下程序才会执行else的语句
举个例子:
def divide(x, y): try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause")
自定义异常
可以通过创建一个新的exception类来拥有自己的异常。异常应该继承自 Exception 类,当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:
class Error(Exception): """Base class for exceptions in this module.""" passclass InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, expression, message): self.expression = expression self.message = messageclass TransitionError(Error): """Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """ def __init__(self, previous, next, message): self.previous = previous self.next = next self.message = message预定义的清理行为
用关键字with,可以保证文件对象等在使用完之后一定会正确执行清理方法
with open("test.txt") as f: for line in f: print(line, end="")无论处理过程是否顺利,文件都会关闭
1 0
- Python3学习七之异常处理
- Python3之异常处理
- CSharp学习笔记之七 异常处理
- java学习初探七之异常处理
- Python3学习(29)--异常处理
- Python3.3 学习笔记5 - 异常处理
- SpringMVC学习笔记(七)处理异常
- Python3.2 --- 异常处理
- Python3 的异常处理
- Python3 的异常处理
- python3的异常处理
- Python3 异常处理
- Python3 异常处理
- Python3 异常处理
- python3 异常处理
- python3 异常及异常处理
- Python3学习笔记(4)——异常处理
- c++学习之异常处理
- php如何调用类文件中的函数,不复杂很简单~
- C语言的条件编译#if, #elif, #else, #endif、#ifdef, #ifndef
- C++ 多态 虚函数 纯虚函数 动态、静态转换
- JQuery ajax 前端学习经验
- nagiosxi 监控Linux系统
- Python3学习七之异常处理
- 防火墙:IP+端口,外部访问
- Java十六进制字符串转字节数组
- 第八周拓展实践4 年龄几何
- 多继承 菱形继承
- 深度学习与传统机器学习的关系
- css 控制img大小
- anaconda opencv环境配置
- np.linalg