-1

I have a function 'zero' that i cannot change it or add line.

def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

def main():
   zero(10,5)
   zero(10,0)

in the main function I want to call to the zero function and know if the function call the exception or not.

zach
  • 5
  • 1
  • in python the best practice is to use the raise statement. This question is explained in detail in this older topic: https://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python – João Machado Sep 20 '21 at 08:27
  • i can't add line to the zero function so i can't add the raise line into the function – zach Sep 20 '21 at 08:54

3 Answers3

1

Given the restriction that you cannot change zero() in any way (which is the correct way to do it), then you can redirect stdout and parse the output.

import sys
import io


def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

if __name__ == '__main__':
    old_stdout = sys.stdout
    for x, y in [(5, 0), (10, 2), (10, 0)]:
        new_stdout = io.StringIO()
        sys.stdout = new_stdout
        zero(x, y)
        result = new_stdout.getvalue().strip()
        if result:
            print(f'Division {x}/{y} raise an error:{result}', file=old_stdout)
    sys.stdout = old_stdout

output

Division 5/0 raise an error:cannot divide by zero
Division 10/0 raise an error:cannot divide by zero
buran
  • 13,682
  • 10
  • 36
  • 61
0

You could return the result of the division, or the exception using the following:

def zero(a, b):
    try:
        num = a / b
    except:
        num="cannot divide by zero"
    return num

This would allow you to compare the result within your main function and determine if the exception was called.

G Ritchie
  • 146
  • 2
  • 12
0

This is a weird requirement because the function always returns None, because num is a local variable and the function does not return it. So you can't even figure out that there was an exception by having a global variable num without adding a global statement to the function.

This approach will work, though I have a poor opinion of the question:

def zero(a, b):
    try:
        num = a / b
    except:
        print("cannot divide by zero")

def print(error):
    raise ValueError(error)

>>> zero(10,5)
>>> zero(10,0)
Traceback (most recent call last):
  File "<pyshell#1>", line 3, in zero
    num = a / b
ZeroDivisionError: division by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    zero(10,0)
  File "<pyshell#1>", line 5, in zero
    print("cannot divide by zero")
  File "<pyshell#11>", line 2, in print
    raise ValueError(error)
ValueError: cannot divide by zero

The function zero() is very poorly coded, and forcing you to use it unchanged has little educational benefit that I can see, except maybe to drive home the point that bare except clauses are a bad idea.

This answer is similar in spirit to @buran's answer. They both involve changing the behaviour of print() to deliver the information you want outside of the function.

BoarGules
  • 16,440
  • 2
  • 27
  • 44
  • i just simplify the function that i need to work , but the spirit is the same if the function success it would print nothing but if not it will go to the exception and print something – zach Sep 20 '21 at 09:52
  • @zach Well, maybe you *over*simplified it, and in the process made nonsense of the original requirement. – BoarGules Sep 20 '21 at 09:55