Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to handle python exception inside if statement?

I have the following code with an exception inside if statement

a,b =5, 0
try:
   if b != 0:
       print a/b
   else:
       raise ZeroDivisionError
except Exception as e:
       print e

I am not able to catch the exception. How to catch the exception?


1 Answer
Rajendra Dharmkar

The code can be written as follows to catch the exception

a, b=5, 0
try:
   if b != 0:
       print a/b
   else:
       a/b
       raise ZeroDivisionError
except Exception as e:
       print e

We get the following output

C:/Users/TutorialsPoint1/~.py
integer division or modulo by zero
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.