Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NetworkX, How do I successfully catch network.exception.NetworkXError when node is not in the graph?

When a node is not in the graph I get and exception error. As I try to catch and handle it, I can't (so I must be doing something wrong). How do I catch and handle networkx.exception.NetworkXError?

Here is the error:

<snip> raise NetworkXError("The node %s is not in the digraph."%(n,)) networkx.exception.NetworkXError: The node 33293542 is not in the digraph.

Here is how I've tried to catch it and handle it:

try:
    path_len = nx.shortest_path_length(G,uNode, vNode)
except (nx.NetworkXNoPath, nx.exception.NetworkXError) as e:
    print e
    continue 

I have also tried:

try:
        path_len = nx.shortest_path_length(G,uNode, vNode)
except (nx.NetworkXNoPath, KeyError) as e:
        print e
        continue 

I maintain uNode and vNode in two lists, I could do a: if v in target_nodes:, but before I do that, I was wondering if there is an elegant way to handle this NetworkX exception?

like image 362
sAguinaga Avatar asked May 21 '15 10:05

sAguinaga


Video Answer


1 Answers

If all you're doing is ensuring you don't try to get the path length of a non-existent node then why not just use has_node:

if G.has_node(uNode) and G.has_node(vNode):
    path_len = nx.shortest_path_length(G,uNode, vNode)

EDIT

The following worked for me:

In [76]:    
import networkx as nx
G=nx.Graph()
G.add_edge(2,3)
try:
    nx.shortest_path_length(G,0,1)
except nx.NetworkXError:
    print("not found")

not found
like image 86
EdChum Avatar answered Sep 28 '22 10:09

EdChum