Python error and exception handling exercises with solution

Error and Exception handling blog post here

Question 1: Perfect division function

Write a function division() that accepts two arguments. The function should be able to catch an exception such as ZeroDivisionError, ValueError, or any unknown error you might come across when you are doing a division operation.

Source code:

def division(x,y):
    try:
        div = x/y
        print(f"{x}/{y} = {div}")
    except ZeroDivisionError as e:
        print("Exception occurred!:", e)
    except Exception as e:
        print("Exception occurred!:", e)
a = int(input("Enter number a: "))
b = int(input("Enter number b: "))
division(a,b)

Output:

Output sample 1
Enter number a: 10
Enter number b: 5
10/5 = 2.0

Output sample 2
Enter number a: 10
Enter number b: 0
Exception occurred!: division by zero
Question 2: Perfect division function with clean-up action

Modify the earlier “perfect division function” task in such a way that the function division() has a clean-up action.

Source code:

def division(x,y):
    try:
        div = x/y
        print(f"{x}/{y} = {div}")
    except ZeroDivisionError as e:
        print("Exception occurred!:", e)
    except Exception as e:
        print("Exception occurred!:", e)
    finally:
        print("Working on division function.")
a = int(input("Enter number a: "))
b = int(input("Enter number b: "))
division(a,b)

Output:

Output sample 1
Enter number a: 10
Enter number b: 5
10/5 = 2.0
Working on division function.

Output sample 2
Enter number a: 10
Enter number b: 0
Exception occurred!: division by zero
Working on division function.