Search code examples
pythongraphnetworkxcycle

python, How can I put and if to a function that raise an error?


Hi all I am checking for cycle in the graph

import networkx as nx
X2 = {"1": ["4"], "2": ["3"], "3": ["2", "4"], "4": ["1", "3"]}
L2 = []
for k,v in X2.items():
    for i in range(len(v)):
        L2.append((k,v[i]))
print(L2)
G = nx.DiGraph(L2)
G = G.to_undirected()

print(type(G))
print(nx.find_cycle(G))

In this case correctly there aren't cycle so the nx function raise:

raise nx.exception.NetworkXNoCycle('No cycle found.')
networkx.exception.NetworkXNoCycle: No cycle found.

How can I put and If condition to print something if the function raise me the error?


Solution

  • What you are looking for here is error handling. It works like an if for errors like you want.

    You achieve this with a try/except block. More details here.

    import networkx as nx
    X2 = {"1": ["4"], "2": ["3"], "3": ["2", "4"], "4": ["1", "3"]}
    L2 = []
    for k,v in X2.items():
        for i in range(len(v)):
            L2.append((k,v[i]))
    print(L2)
    try:
        G = nx.DiGraph(L2)
        G = G.to_undirected()
        print(type(G))
        print(nx.find_cycle(G))
    except:
        print("Error message")