Test with try-except for Invocation
In this step, you will learn how to use try-except
blocks to handle potential errors when calling objects in Python. This is particularly useful when you are not sure if an object is callable or if calling it might raise an exception.
Let's start with an example where we attempt to call an object that might not be callable:
def my_function():
return "Hello from my_function!"
x = 10
objects_to_test = [my_function, x]
for obj in objects_to_test:
try:
result = obj()
print(f"Object is callable, result: {result}")
except TypeError as e:
print(f"Object is not callable: {e}")
Add this code to your callable_example.py
file, replacing the previous content.
Now, execute the script using the following command in the terminal:
python callable_example.py
You should see the following output:
Object is callable, result: Hello from my_function!
Object is not callable: 'int' object is not callable
In this example, we iterate through a list of objects, attempting to call each one. The try
block attempts to call the object. If the object is callable and the call is successful, the result is printed. If the object is not callable, a TypeError
is raised, and the except
block catches the exception and prints an appropriate message.
Now, let's consider a case where the object is callable, but calling it might raise a different type of exception:
def my_function(a, b):
return a / b
try:
result = my_function(10, 0)
print(f"Result: {result}")
except ZeroDivisionError as e:
print(f"Error: {e}")
except TypeError as e:
print(f"Error: {e}")
Add this code to your callable_example.py
file, replacing the previous content.
Execute the script again:
python callable_example.py
You should see the following output:
Error: division by zero
In this case, my_function
is callable, but calling it with b = 0
raises a ZeroDivisionError
. The try-except
block catches this specific exception and handles it gracefully.
Using try-except
blocks allows you to write more robust and reliable code by anticipating and handling potential errors that might occur when calling objects.