0

Is there any way to do this without a lot of try/excepts? I have more than 30 divisions and my code is very long with all try/except

def test():
    a = 12
    b = 0
    c = 43
    d = 0
    try:
        w = a / b
    except Exception:
        w = 'cant'
    try:
        x = b / c
    except Exception:
        x = 'cant'
    try:
        y = c / d
    except Exception:
        y = 'cant'
    print(w)
    print(x)
    print(y)
Martin Bouhier
  • 173
  • 1
  • 10
  • You can put all the "tries" into one statement and catch with a single Exception if that is what you want. E.g. `try: w = .. , x =..., y = ..., except Exception: ...` – k88 Dec 06 '19 at 05:25
  • Does this answer your question? [Catch multiple exceptions in one line (except block)](https://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block) – Raksha Saini Feb 02 '21 at 05:12

3 Answers3

2

When you want to do the same thing three times with different values, factor it out into a function. Note that you don't need to catch an error here; you can use if/else to test whether the division will work before doing it:

def divide_or_cant(p, q):
    if q == 0:
        return 'cant'
    else:
        return p / q

def test():
    a = 12
    b = 0
    c = 43
    d = 0
    w = divide_or_cant(a, b)
    x = divide_or_cant(b, c)
    y = divide_or_cant(c, d)
    print(w)
    print(x)
    print(y)

If you want to do this 30 times then you are much better off putting the data into a list and writing a loop:

def test():
    nums = [12, 0, 43, 0]
    for a, b in zip(nums, nums[1:]):
        r = divide_or_cant(a, b)
        print(r)
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • From the same glossary: *"Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements."* Both are just descriptions of coding styles, not recommendations; I recommend using `if` where you can. For a performance comparison, the version using `if` is about twice as fast on my machine. – kaya3 Dec 06 '19 at 05:39
  • I didn't quote the whole entry because the rest is not relevant. The value of the parameter `b` cannot be changed by another thread in between the `if` statement and the division; it is a local variable referencing an immutable object. – kaya3 Dec 06 '19 at 06:09
  • Sorry to have upset you. I've deleted my comments as not constructive. I was trying inartfully to respond to the suggestion against a common style in python. If you are interested in reading more, there are clearly good uses of each style: https://stackoverflow.com/questions/1835756/using-try-vs-if-in-python. – AChampion Dec 06 '19 at 06:21
  • Don't worry, you didn't upset me. I agree that there are times where `try`/`catch` is much better than `if`/`else`. – kaya3 Dec 06 '19 at 15:06
1

In your case you can define a function to achieve this:

def divide(a, b):
    try:
        return a / b
    except:
        return 'cant'

def test():
    a = 12
    b = 0
    c = 43
    d = 0
    w = divide(a, b)
    x = divide(b, c)
    y = divide(c, d)
    print(w)
    print(x)
    print(y)
Pavel Shishmarev
  • 1,335
  • 9
  • 24
1

Code:

def try_or_error(supplier, msg):
    try:
        return supplier()
    except:
        return msg


def test():
    a = 12
    b = 0
    c = 43
    d = 0
    w = try_or_error(lambda: a / b, 'cant')
    x = try_or_error(lambda: b / c, 'cant')
    y = try_or_error(lambda: c / d, 'cant')
    print(w)
    print(x)
    print(y)


if __name__ == '__main__':
    test()
BaiJiFeiLong
  • 3,716
  • 1
  • 30
  • 28