Explore Exceptions in Functions
In this step, you will learn about exceptions and how they can occur within functions in Python. Understanding exceptions is crucial for writing robust and reliable code. Exceptions are events that disrupt the normal flow of a program's execution. They can occur due to various reasons, such as invalid input, file not found, or network errors.
Let's start by creating a simple Python function that might raise an exception. Open the VS Code editor in the LabEx environment and create a new file named exceptions_example.py
in the ~/project
directory.
## ~/project/exceptions_example.py
def divide(x, y):
return x / y
print(divide(10, 2))
print(divide(5, 0))
In this code:
- We define a function called
divide
that takes two arguments, x
and y
, and returns the result of x
divided by y
.
- We first call the
divide
function with the arguments 10
and 2
, which will result in 5.0
being printed to the console.
- Then, we call the
divide
function with the arguments 5
and 0
. This will cause a ZeroDivisionError
because division by zero is not allowed.
Now, let's run this script. Open the terminal in VS Code (you can find it under "View" -> "Terminal") and execute the following command:
python ~/project/exceptions_example.py
You will see output similar to this:
5.0
Traceback (most recent call last):
File "/home/labex/project/exceptions_example.py", line 4, in <module>
print(divide(5, 0))
File "/home/labex/project/exceptions_example.py", line 2, in divide
return x / y
ZeroDivisionError: division by zero
As you can see, the first print
statement executed successfully, and the result 5.0
was printed. However, when the divide
function was called with y = 0
, a ZeroDivisionError
occurred, and the program terminated. The traceback shows the sequence of function calls that led to the exception, which can be helpful for debugging.
This example demonstrates how exceptions can occur within functions and how they can disrupt the normal flow of a program. In the next step, you will learn how to handle exceptions using try
and except
blocks.