如何使这种异常处理更简单?
How can this excepction handling be made simpler?
我有等价于下面的代码:
class SomeError(Exception): pass
def do_things_with(fileobject):
# Do things, and at some point the line below MAY be called
raise SomeError
def try_another_approach():
# Do different things, but at some point the line below MAY be called
raise SomeError
try:
try:
with open('somefile') as somefile:
do_things_with(somefile)
except FileNotFoundError:
try_another_approach()
except SomeError:
print('Ooops')
也就是说,我尝试打开一个文件(或任何其他可能引发某些其他异常的东西),如果失败,可能会使用不同的方法,但两种方法都可能引发同一组异常。
现在我必须用嵌套的 try/except 来处理这个问题,如图所示,但我很想做这样的事情:
try:
with open('somefile') as somefile:
do_things_with(somefile)
except FileNotFoundError:
# I'd like to have any SomeError raised from the function below
# at the except clause just below, to keep code compact as I may
# be adding more exceptions in the future
try_another_approach()
except SomeError:
print('Ooops')
当然这行不通(我得到了其中一个 During handling of the above exception, another exception occurred
),但它说明了我想要实现的目标:处理在 try 块和某些块中引发的异常except 块与后面的 except 块,没有嵌套.
我不需要避免嵌套,我只是想知道有什么方法可以解决这个问题而不必嵌套,以防万一。
Python 有可能吗?
提前致谢:)
不,你不能。在 except 子句中引发的异常将在外部块中寻找处理程序(即您所做的嵌套)。如果在您当前的方法中没有嵌套,则没有其他方法可以解决此问题。
消除嵌套的唯一方法是减少异常;也就是说,您 return
不是 raise Error
而是一个值,表示出现问题。在这种情况下,您对返回值(使用 if
子句)进行操作,而不是对返回的异常(使用 try-except
子句)进行操作。
我有等价于下面的代码:
class SomeError(Exception): pass
def do_things_with(fileobject):
# Do things, and at some point the line below MAY be called
raise SomeError
def try_another_approach():
# Do different things, but at some point the line below MAY be called
raise SomeError
try:
try:
with open('somefile') as somefile:
do_things_with(somefile)
except FileNotFoundError:
try_another_approach()
except SomeError:
print('Ooops')
也就是说,我尝试打开一个文件(或任何其他可能引发某些其他异常的东西),如果失败,可能会使用不同的方法,但两种方法都可能引发同一组异常。
现在我必须用嵌套的 try/except 来处理这个问题,如图所示,但我很想做这样的事情:
try:
with open('somefile') as somefile:
do_things_with(somefile)
except FileNotFoundError:
# I'd like to have any SomeError raised from the function below
# at the except clause just below, to keep code compact as I may
# be adding more exceptions in the future
try_another_approach()
except SomeError:
print('Ooops')
当然这行不通(我得到了其中一个 During handling of the above exception, another exception occurred
),但它说明了我想要实现的目标:处理在 try 块和某些块中引发的异常except 块与后面的 except 块,没有嵌套.
我不需要避免嵌套,我只是想知道有什么方法可以解决这个问题而不必嵌套,以防万一。
Python 有可能吗?
提前致谢:)
不,你不能。在 except 子句中引发的异常将在外部块中寻找处理程序(即您所做的嵌套)。如果在您当前的方法中没有嵌套,则没有其他方法可以解决此问题。
消除嵌套的唯一方法是减少异常;也就是说,您 return
不是 raise Error
而是一个值,表示出现问题。在这种情况下,您对返回值(使用 if
子句)进行操作,而不是对返回的异常(使用 try-except
子句)进行操作。