try 函数出现显式异常问题



无论代码是否失败,我都必须运行代码。我正在使用ExplicitException.以下是我的代码:

try:
G.add_edge(data1[0][0],data1[1][0],weight=data1[2+i][0])
except ExplicitException:
pass
try:
G.add_edge(data1[0][0],data1[5][0],weight=data1[6+i][0])
except ExplicitException:
pass
try:
G.add_edge(data1[0][0],data1[9][0],weight=data1[10+i][0])
except ExplicitException:
pass   
try:
G.add_edge(data1[0][0],data1[13][0],weight=data1[14+i][0])
except ExplicitException:
pass   

我收到以下错误:

名称

错误:未定义名称"显式异常">

将不胜感激

我想你从这个答案中得到了这个想法。答案试图传达的想法是,您可以使用您选择的例外。实际上,没有像ExplicitException这样的例外。可以使用内置中的任何异常,也可以定义自己的异常类。

您还可以除基类Exception和所有例外情况外。

try:
# code
except Exception:
pass

编辑:虽然您可以添加多个 try-except 块,但这不是一个好的做法。在您的情况下,我相信您的异常是因为i的一些无效值会抛出越界异常。因此,您可以通过在 if-else 条件下检查正确的i值来避免这种情况。

如果您真的喜欢使用 try-except,请尝试概括这些线并将它们合并到一个循环中。这将使错误处理更容易。例如,在上述案例中:

for j in range(1,14,4):
try:
G.add_edge(data1[0][0],data1[j][0],weight=data1[1+j+i][0])
except:
pass

没有ExplicitException,在注释中链接的线程中,OP 指的是显式异常类型。由于代码是重复的,你可以构建一个函数并使用它

def add_edge(first_indices, second_indices, weight_indices):
try:
G.add_edge(data1[first_indices[0]][first_indices[1]], data1[second_indices[0]][second_indices[1]], weight=data1[weight_indices[0]][weight_indices[1]])
except (IndexError, TypeError):  # example to explicit exception
pass
add_edge([0, 0], [1, 0], [2 + i, 0])
add_edge([0, 0], [5, 0], [6 + i, 0])
add_edge([0, 0], [9, 0], [10 + i, 0])
add_edge([0, 0], [13, 0], [14 + i, 0])

最新更新