3

So I've got something of the form:

def func():
  while True:
    do_stuff()

try:
  func()
except:
  func()

I had expected that if anything happened to my func loop, it would start again, however in actual fact errors cause it to crash. How can I make it just restart if anything goes wrong?

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • 1
    I think you should rely on shell script for this matter. – Nihal Feb 06 '19 at 08:11
  • 4
    So you program will still work on out of memory exceptions? – RedX Feb 06 '19 at 08:14
  • @RedX can we do it like: use all the exception except `out of memory` exception? in python? – Nihal Feb 06 '19 at 08:16
  • 4
    @Nihal Of course you can always make a whitelist or blacklist but my point is that the simple requirement shows no real thought and should be reconsidered. – RedX Feb 06 '19 at 08:19

3 Answers3

4

You can try placing the try-except inside a while loop and use pass in the except block.

Ex:

def func():
  while True:
    do_stuff()

while True:
    try:
        func()
    except:
        pass
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

What are you trying to achieve? Keeping a program run is generally not the responsibility of the program itself. If you are on a UNIX-like operating system, you can use Supervisord to automatically run processes and let them restart if they fail. If you are on Windows, this answer may help you out!

0

Try to put loop contents inside try except statements

def func():
    while True:
        try:
            do_stuff()
        except:
            continue
func()
Akshay Nailwal
  • 196
  • 1
  • 9