Falmarri
Falmarri

Reputation: 48577

Using a try/catch to retry the same method

I have a class whose methods require that a certain class field exists correctly. That class field is set in the constructor and it's read from a config file, and it may or may not get the correct data from that config file. If the data is incorrect, it will have the wrong data in the class field and the class method will throw an exception.

If that happens, what I want to do is run the method again but with a different call to the class constructor. Is this something that is reasonably handled in a try:catch? Because the method MAY throw the same exception even with the correct class field. So what I want is to have the first time the method is called, the exception is caught and then the method run again. But on the 2nd run if the exception is thrown I want it to propagate. So:


try:
    MyClass().method()
except MyException:
    MyClass(True).method()

Is there an obvious flaw to this? Or a better way to do this without using counters, or flags, or other ugly helper objects?

Upvotes: 2

Views: 596

Answers (3)

dmitko
dmitko

Reputation: 2657

Sounds like you're talking about sort of Factory method. I would create a separate Creator class to handle such situation.

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881735

I'm a bit surprised that you don't want the MyClass instance to stick around for later use, but, given that this is your intention, your code is correct and concise -- it does what you state you want without any "obvious flaw". I'm not sure which objects you think ugly and which ones you think pretty, but without introducing some "helper objects" I can't even think of another way to achieve your stated requirements!-)

Upvotes: 3

Tamás
Tamás

Reputation: 48071

What you're doing is fine; if the method throws the same exception from within the exception handler, it will be propagated and not caught by the same handler.

Upvotes: 1

Related Questions