提出子例外的好方法是什么(这是该术语)? 场景: 我想在发生http或ftp异常时引发自定义ConnectivityException。有没有办法提出ConnectivityException,以便异常被正确分类(即我应该能够判断是否因为http ot ftp而引发了ConnectivityException)?
答案 0 :(得分:3)
标准技术是将ConnectivityException
子类化为特定于每种错误条件的异常类:
class ConnectivityException(Exception): pass
class HTTPConnectivityException(ConnectivityException): pass
class FTPConnectivityException(ConnectivityException): pass
然后,您可以使用raise ConnectivityException
或raise HTTPConnectivityException
代替raise FTPConnectivityException
,具体取决于您要指明的特定类型的错误。
可以使用多个异常块根据异常类型分派错误处理:
try:
some_network_operation()
except HTTPConnectivityException as ex:
# This will execute if the error is an HTTPConnectivityException.
except FTPConnectivityException as ex:
# Likewise for FTPConnectivityException.
except ConnectivityException as ex:
# The generic case; this block will execute if the ConnectivityException isn't
# an instance of one of the earlier specified subclasses.
请注意,异常处理块以词法顺序尝试;将使用指定异常对象所属的类的第一个块。在这种情况下,这意味着您需要将ConnectivityException
块放在最后,否则它也会捕获HTTPConnectivityException
和FTPConnectivityException
。
答案 1 :(得分:1)
您可以添加名为' source'的属性到ConnectivityException,并将其设置为' http'或者' ftp'根据具体情况,当捕获ConnectivityException时,检查source属性并决定做什么
这里我推荐另一种使用继承类
的方法class ConnectivityException(Exception):
pass # you can define some attributes and methods, here I just escape
class HTTPConnectivityException(ConnectivityException):
pass
class FTPConnectivityException(ConnectivityException):
pass
def func():
if some_condition:
raise HTTPConnectivityException()
if some_other_condition:
raise FTPConnectivityException()
def another_func():
try:
func()
except HTTPConnectivityException as e:
pass # you can do something here
except FTPConnectivityException as e:
pass