If you code in Python than, you have probably already worked with a lot of try and except blocks. In this blog, we will explore some of the hidden functionality of these blocks. We will demonstrate this by creating a function called divide, which divides a by b and returns a string. We will handle two specific exceptions: ZeroDivisionError if the user divides by zero, and TypeError if they enter a non-numeric value. Let's run the program to test it out.
def divide(a, b):
try:
result = a / b
return str(result)
except ZeroDivisionError:
return "Error: Division by zero"
except TypeError:
return "Error: Invalid input"
print(divide(10, 4)) # Output: 2.5
print(divide(10, 'a')) # Output: Error: Invalid input
print(divide(10, 0)) # Output: Error: Division by zero
Hidden Functionality: else Block
Now, let’s explore the else block in a try and except block. If the code in the try block runs successfully without encountering any exceptions, everything in the else block will be executed. This provides an opportunity to add additional functionality. For example, we can print a success message. Let's modify our code to include the else block.