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])
except ExplicitException:passtry:G.add_edge(data1[0][0],data1[5][0],weight=data1[6+i][0])
except ExplicitException:passtry: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
I'm getting the following error:
NameError: name 'ExplicitException' is not defined
would appreciate some help
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:# code
except 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 in range(1,14,4):try:G.add_edge(data1[0][0],data1[j][0],weight=data1[1+j+i][0])except:pass