-2

As the title states – instead of printing the exception, is it good practice to execute code in the except clause, which solves the error raised in the try clause?

For example, I'm creating a wrapper for Mininet, which creates some network topology. However, if the previous instance of the network topology isn't stopped, the creation fails, and the previous network must be cleaned up before the creation can succeed. This is done by executing the Mininet CLI command sudo mn -c. See the code below.

class MininetWrapper:
    def __init__(self):
        try:
            self.net = Mininet(topo=<topology>, controller=<controller>)
        except:
            os.system('sudo mn -c')
            self.net = Mininet(topo=<topology>, controller=<controller>)
        self.net.start()

If the above is not good practice, please suggest a better method.

s164151
  • 19
  • 4
  • Since the purpose of the try, except construct is to process error conditions in a clean manner, inserting code which corrects the error seems to be within the scope of the except clause. – itprorh66 Jun 21 '21 at 19:29

2 Answers2

1

Executing code, sure. Blindly excepting all exceptions, almost definitely not. Rerunning the same code, probably a better way.

IMO except clauses are for when things aren't as you expect, but you don't want the system to suddenly fail. Instead you want to handle the error correctly.

In your case, one of the things you expect to happen is wanting to create an instance of this class when the previous network topology hasn't been stopped. So you should have the allowance for this already, and then have an except clause when something unexpected happens.

If you never what to have the previous thing running, why not always clean up the previous network? I looks like the API has a function for this already.

I would do something like:

class MininetWrapper:
    def __init__(self):
        Cleanup.cleanup()
        self.net = Mininet(topo=<topology>, controller=<controller>)
        self.net.start()

Notice I'm not catching any error because I don't expect anything to be wrong. If something is wrong now, I want the program to raise it.

blueteeth
  • 3,330
  • 1
  • 13
  • 23
0

Of course you can !

In fact, this is not "good practice" but just normal : except is made for handling and correcting exceptions...

todev
  • 27
  • 5