Python programs consist of functions and methods that call each other. Information about which function calls which is stored in an area of memory that Python allocates known as the call stack.
If an exception is raised you can catch the exception anywhere up the call stack.
So if a function a() calls b() which calls c() which raises an exception, you can catch the exception in b() or in a().
To catch exceptions we use a try … except construct.
In this program, the calculate_area() function raises an exception which we catch in the main() function.
def calculate_area(length, width):
if length < 0:
raise ValueError("Length parameter cannot be negative.")
if width < 0:
raise ValueError("Width parameter cannot be negative.")
return length * width
def main():
try:
area = calculate_area(5, -1)
print(f"The area is {area} square metres")
except:
print("Area could not be calculated.")
main()
Area could not be calculated.
At the point where the exception is raised, program execution immediately jumps out of the function where raise is executed. The exception bubbles up the call stack until it’s eventually caught, or else jumps out of the top level function (main, in this case), where it causes a traceback.
By catching it you can prevent the traceback occurring and handle it in your own way.
Leave a Reply