Exception handling is important to prevent crashes. For instance, consider the code below. The function division()
simply divides two arguments and returns the result. If you pass the second argument as zero, the program will crash and will throw ZeroDivisionError
.
ZeroDivisionError: division by zero
def division(dividend, divisor):
return dividend / divisor
result = division(5,0)
Instead, you can catch ZeroDivisionError using try/except
block and display an appropriate message rather than crashing the program.
In the following code, you can find an updated version of the division()
function. The code is moved inside try/except block. In case ZeroDivisionError
is thrown, except block will execute and function will return the specified message.
def division(dividend, divisor):
try:
return dividend / divisor
except ZeroDivisionError:
return "Divisor cannot be zero"
print(division(6,2)) # 3
print(division(6,0)) # Divisor cannot be zero
Else Block
Except block executes when an exception is thrown in try
code block. Conversely, else block executes when no exception is thrown in try
code block.
def counter():
""" Prints numbers from 1 to 10 """
try:
for num in range(1,11):
print(num)
except:
print("There is an error. Something unexpected happened.")
else:
print("Function executed properly without an error.")
Finally Block
finally
block executes, whether or not an exception is thrown in try
block.
In the following code, a file is opened. File should be closed even if an exception is raised in try block. The close()
method is called in finally
block because finally block is executed no matter an exception is thrown or not.
try:
f = open("a_text_file.txt")
f.write("a new line")
except IOError:
print("An error is raised when accessing the file.")
finally:
f.close()
Raising an Exception
Sometimes, you might need to raise your own exception. You can use raise
keyword to raise custom exceptions.
def rate_the_course(rating):
if (rating < 1) or (rating > 5):
raise Exception("Your rating should be between 1 and 5")
print("Thank you for your rating!")