Skip to content Skip to sidebar Skip to footer

Explicit Exception Problem With Try Function

I have to run codes irrespective whether it fails or not. I'm using ExplicitException. Following is my code: try: G.add_edge(data1[0][0],data1[1][0],weight=data1[2+i][0]) excep

Solution 1:

I guess you got that idea from this answer. The idea the answer was trying to convey was that you can use an exception of your choice. In reality, there is no such exception as ExplicitException. You can use any exception from the built-ins or define your own exception class.

You can also except the base class Exception and except all exceptions.

try:
    # codeexcept Exception:
    pass

EDIT: While you can go about adding multiple try-except blocks, it is not a good practice. In your case, I believe your exception is because of some invalid value of i which would throw out of bounds exception. So you can avoid this by checking for the right values of i in if-else conditions.

If you're really into using try-except, try generalizing the lines and consolidating them into a loop. That would make the error handling easier. For example in the case above:

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

Solution 2:

There is no ExplicitException, in the thread you linked in the comments the OP is referring to explicit exception type. Since the code is repeating itself you can build a function and use it

defadd_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 exceptionpass

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])

Post a Comment for "Explicit Exception Problem With Try Function"