Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading