exceptions模块中文文档
发布时间:2023-12-17 05:17:26
exceptions模块是Python中用于处理异常的标准模块之一。它提供了一些内置的异常类,用于处理常见的错误情况和异常情况。本文将介绍exceptions模块中各个异常类的使用方法,并附上一些示例代码。
1. BaseException:是所有异常类的父类,它提供了一些通用的方法和属性,如args属性可获取异常消息的参数元组。
try:
raise BaseException("Something went wrong")
except BaseException as e:
print(e.args) # 输出:('Something went wrong',)
2. Exception:是继承自BaseException的异常基类,是大多数异常类的父类。可以用它来捕捉大部分常见的异常。
try:
raise Exception("Something went wrong")
except Exception as e:
print(e.args) # 输出:('Something went wrong',)
3. AssertionError:用于处理断言失败时引发的异常。
try:
assert 2 + 2 == 5
except AssertionError:
print("Assertion failed") # 输出:Assertion failed
4. AttributeError:用于处理对象没有特定属性时引发的异常。
class MyClass():
pass
obj = MyClass()
try:
obj.some_attribute
except AttributeError:
print("Attribute does not exist") # 输出:Attribute does not exist
5. EOFError:用于处理读取文件或输入流到达文件末尾时引发的异常。
try:
while True:
line = input()
print(line)
except EOFError:
print("End of file reached")
6. ImportError:用于处理导入模块失败时引发的异常。
try:
import non_existing_module
except ImportError:
print("Module does not exist") # 输出:Module does not exist
7. IndexError:用于处理索引超出序列范围时引发的异常。
my_list = [1, 2, 3]
try:
print(my_list[4])
except IndexError:
print("Index out of range") # 输出:Index out of range
8. KeyError:用于处理字典中查找不存在的键时引发的异常。
my_dict = {"key1": "value1", "key2": "value2"}
try:
print(my_dict["key3"])
except KeyError:
print("Key does not exist") # 输出:Key does not exist
9. NameError:用于处理使用不存在的变量或函数时引发的异常。
try:
print(non_existing_variable)
except NameError:
print("Variable does not exist") # 输出:Variable does not exist
10. NotImplementedError:用于处理尚未实现的方法或函数时引发的异常。
class MyBaseClass():
def my_method(self):
raise NotImplementedError("Method not implemented")
obj = MyBaseClass()
try:
obj.my_method()
except NotImplementedError as e:
print(e.args) # 输出:('Method not implemented',)
这些只是exceptions模块中部分异常类的用法示例,还有很多其他的异常类可以用于处理不同的异常情况。希望本文能够帮助你理解exceptions模块的基本用法,并且能够在实际编程中正确处理异常。
