Instead, you can catch ZeroDivisionError using
try/except block and display an appropriate message rather than crashing the program.
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
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 executes, whether or not an exception is thrown in
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
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!")