您有两个基本选择:
- 将
handle_exceptions 视为布尔值,如果False 则重新加注
- 将
handle_exceptions 视为要处理的异常
沿着布尔路径,您有两个基本选择:
def my_func(my_arg, handle_exceptions):
try:
do_something(my_arg)
except Exception, e:
if not handle_exceptions:
raise
print "my_func is handling the exception"
或
def my_func(my_arg, handle_exceptions):
if handle_exceptions:
exceptions = ValueError, IndexError # or whatever
else:
exceptions = NoExceptions # None in 2.x, or custom Exception class in 3.x
try:
do_something(my_arg)
except exceptions, e:
print "my_func is handling the exception"
沿着“将handle_exceptions 视为要处理的例外”路线,您可以这样做:
class NoExceptions(Exception):
'Dummy exception, never raised'
def my_func(my_arg, handle_exceptions=NoExceptions):
try:
do_something(my_arg)
except handle_exceptions, e:
print "my_func is handling the exception"
你会这样称呼它:
my_func(some_arg, ValueError) # to handle ValueErrors
或
my_func(some_arg) # to not handle any exeptions
这具有调用者能够指定处理哪些异常的优点/缺点。如果您确实采取了最后一条路线,您可能还想指定一个异常处理程序,可能是这样的:
def my_func(my_arg, handle_exceptions=NoExceptions, handler=None):
try:
do_something(my_arg)
except handle_exceptions, e:
if handler is not None:
handler(e)
else:
log_this_exception()