0

I'm working on a program that generates random equations and always get errors such as "cannot divide by zero" and "overflowerror: result too large" that prevent the generating from continuing. Is there a way to prevent the program from freezing and getting error messages?

import random
import math

while 1:
    try:

        var = ['math.pi','999999999999999999999','(5/3)']

        s1 = '**'
        s2 = '**'
        s3 = '**'
        s4 = '**'

        v1 = var[random.randrange(0,2)]
        v2 = var[random.randrange(0,2)]
        v3 = var[random.randrange(0,2)]
        v4 = var[random.randrange(0,2)]
        v5 = var[random.randrange(0,2)]

        result = eval(v1+s1+v2+s2+v3+s3+v4+s4+v5)
        print v1+s+v2+s+v3+s+v4+s+v5

    except:
        print("error found moving on")
  • @zar try-except works with errors but the program still freezes without errors showing up. How do prevent it from freezing? – user5283660 Sep 01 '15 at 01:31
  • 1
    Please post a [mcve] Otherwise we can't figure out what's going on. – theB Sep 01 '15 at 01:37
  • I posted an answer, you can reply to this comment by commenting on the answer instead. To see why it's freezing you need to post your code, it is probably happening because you aren't handling your except statement properly. – Zarwan Sep 01 '15 at 03:00
  • You're in an infinite loop, so your program will crash. – Zarwan Sep 01 '15 at 03:55
  • @Zar how do I fix it? – user5283660 Sep 01 '15 at 03:56
  • Well you have to decide how many times you want your while loop to run, because right now it will never end. Also, this probably has to do with the exceptions you are now ignoring (which is why I did not recommend this solution), you should address your overflow error: http://stackoverflow.com/questions/20201706/overflowerror-34-result-too-large – Zarwan Sep 01 '15 at 03:57
  • 1
    @Zar: `try` and `except` are fine. Look at ["What is the EAFP principle in Python?"](http://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python). – Matthias Sep 01 '15 at 06:22
  • @Matthias thanks, I didn't know that. I'm used to Java where having them in your flow is usually discouraged. – Zarwan Sep 01 '15 at 06:23

1 Answers1

0

Well, you should look into why the errors are happening in the first place and fix them. But if you want a quick (and unrecommended) solution you can catch the exceptions using a try-except block to prevent your program from crashing. Go to section 8.3 here to see how to do this: https://docs.python.org/2/tutorial/errors.html

Zarwan
  • 5,537
  • 4
  • 30
  • 48