Back to: Python Programming
An exception occurs when an event during execution interrupts the flow of a program.
For example, we are not able to divide by zero in a program. The following code will work fine unless the user enters a zero (0), which will cause an exception:
numerator = int(input("Enter a number to divide: "))
denominator = int(input("Enter a number to divide by: "))
result = numerator / denominator
print(result)
The code above works fine, until a zero appears on the denominator:
Enter a number to divide: 10
Enter a number to divide by: 0
Traceback (most recent call last):
File "C:\Users\pc\PycharmProjects\helloWorld\main.py", line 3, in <module>
result = numerator / denominator
~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
Process finished with exit code 1
To handle these exceptions so they don’t interrupt the flow of a program. The above code is considered dangerous because we don’t know what the user is going to enter.
A simple method to catch the exception (exception handling) is to surround any dangerous code (that has the possibility of causing an exception) within a try block. This will catch the exception and do something else (other than break the flow of the code).
try:
numerator = int(input("Enter a number to divide: "))
denominator = int(input("Enter a number to divide by: "))
result = numerator / denominator
print(result)
except Exception:
print("something went wrong")
If we know the specific exception that is most likely to occur, it is better practice to handle these before using the block that captures ALL exceptions.
try:
numerator = int(input("Enter a number to divide: "))
denominator = int(input("Enter a number to divide by: "))
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("You can't divide by ZERO")
#except Exception:
# print("something went wrong")
If the user types in a word instead of a number, the code will also throw an exception.
try:
numerator = int(input("Enter a number to divide: "))
denominator = int(input("Enter a number to divide by: "))
result = numerator / denominator
except ZeroDivisionError as e: # <-- defines the exception
print(e)
print("You can't divide by zero!")
except ValueError as e:
print(e)
print("Enter only numbers please")
except Exception as e:
print(e)
print("something went wrong :(")
else:
print(result)
finally:
print("This will always execute")