Day 14 - Errors or Exceptions
Everything is fun except when error occurs. Error can come due to any reason. Sometime we forgot to check and assume that everything is fine, but it may not be the case. Then from that assumption error could happen in code. Imagine the below one where we are dividing number a
by number b
. In Mathematics b
can’t be zero. So it will be fine untill b
is zero.
def divide(num1, num2):
print(num1/num2)
divide(20, 2)
divide(30, 10)
divide(40, 0)
divide2(30, 15)
The output would look like,
10.0
3.0
Traceback (most recent call last):
File "for-video.py", line 13, in <module>
divide(40, 0)
File "for-video.py", line 9, in divide
print(num1/num2)
ZeroDivisionError: division by zero
Inside the divide
function we can add an if
condition,
def divide2(num1, num2):
if(num2!=0):
print(num1/num2)
else:
print("Can't be divided by zero")
divide2(20, 2)
divide2(30, 10)
divide2(40, 0)
divide2(30, 15)
The output will look like,
10.0
3.0
Can't be divided by zero
2.0
What happens when error occurs
When error occurs the code terminates. This means the next line onwards it won’t execute any statement.
Error is exception
Error in programming language is known as Exception. We should handle it and then the remaining code lines will get executed.
Handling exception in Python
If you don’t have the check at function then you can handle it while calling.
def divide2(num1, num2):
print(num1/num2)
try:
divide2(20, 2)
except:
print("There is an error")
try:
divide2(40, 0)
except:
print("There is an error")
try:
divide2(30, 15)
except:
print("There is an error")
Output
10.0
There is an error
2.0
This is clearly repeat and we need to avoid any kind of repeat in programming language. By repeat I mean same instruction again and again.
def divide4(num1, num2):
try:
print(num1/num2)
except:
print("There is an error.")
divide4(10, 5)
divide4(9,0)
divide4(30,15)
But it might so happen that you are calling someone else’s function which you can not add any condition then while calling you can use the exception handling. Or make another function to handle error while calling the main function. Like,
#Original function
def divide5(num1, num2):
print(num1/num2)
# Your function calling original function
def divide_error_handled(num1, num2):
try:
divide5(num1, num2)
except:
print("There is an error.")
The code is available.