Welcome! Today, we will manage exceptions within Python functions, much like an astronaut tackling obstacles in space. We will delve into the concept of functions, acquaint ourselves with the handling of exceptions, and investigate their operation during function calls.
Let's take a moment to recap: An exception, an error that can lead to a program crash, can be disruptive. However, a Python function can attempt certain tasks and catch potential exceptions using a try-except-finally
block. This is similar to an astronaut preparing for potential hurdles. Below is an illustration:
Python1def safe_division(x, y): 2 try: 3 return x / y 4 except ZeroDivisionError: 5 print("Warning: Division by zero!")
This function monitors for a ZeroDivisionError
when performing division.
The raise
keyword in Python triggers an exception manually within a function. Consider a function that calculates a square root — an error should occur if the input is negative!
Python1def safe_sqrt(x): 2 if x < 0: 3 raise ValueError("Can't compute square root of a negative number.") 4 else: 5 return x ** 0.5
An exception is raised if a negative input is detected.
The code that calls a function handles any possible exceptions that the function might throw. This is illustrated as follows:
Python1def call_sqrt(): 2 try: 3 print(safe_sqrt(-1)) 4 except ValueError as e: 5 print("Abort mission! Error:", e)
In this scenario, exceptions raised in safe_sqrt
are captured in call_sqrt
.
Exceptions can migrate from one function to another. In nested calls, a raised exception gets passed up the chain; for instance, if fun2
raises exceptions and the except
block does not handle them, they're forwarded to fun1
.
Python1def fun1(): 2 try: 3 fun2() # throws ExceptionType 4 except ExceptionType2: # handling a different exception type 5 # Handle exception
In this scenario, fun1()
might throw ExceptionType
if it occurs, as it's not handled by the except
block.
Congratulations! You've mastered exception handling within Python functions. Up next are practice tasks to sharpen these skills further!
Great job today! You've learned how to handle and manually raise exceptions in Python functions. Next, take on some challenges in the practice tasks to strengthen your understanding and continue exploring the Python universe!