Search code examples
pythonpython-3.xtry-except

Python 3: try/except not working. Am I misunderstanding something here?


I'm new to Python and wanted to try out its exception by a simple dividing function, but the program still crashed and did not catch "Denominator cannot be 0" in the terminal. Any explanation would be great. Thank you!


try:
    def divide(num, deno):
        return num / deno
except ZeroDivisionError:
    print('Denominator cannot be 0')

result = int(divide(6, 0))
print(result)

Expecting the terminal to print out 'Denominator cannot be 0' instead of 'ZeroDevisionError'


Solution

  • Exceptions are raised when the function is called not when the function is defined.

    So you need:

    def divide(num, deno):
        return num / deno
    
    try:
        result = int(divide(6, 0))
        print(result)
    except ZeroDivisionError:
        print('Denominator cannot be 0')
    

    Of course, you are going to have to take care since your result variable will only be defined if divide doesn't raise the exception. But this is the simplest way to modify your code to show you how this could work.