Learn Exception Handling Flow
In this step, you will learn about exception handling in Python. Exception handling is a crucial part of writing robust and reliable code. It allows you to gracefully handle errors that might occur during the execution of your program, preventing it from crashing and providing a more user-friendly experience.
Let's start with a simple example. Imagine you want to divide two numbers, but the second number might be zero. Dividing by zero is an undefined operation and will raise a ZeroDivisionError
in Python.
-
Open the VS Code editor in the LabEx environment.
-
Create a new file named division.py
in the ~/project
directory.
touch ~/project/division.py
-
Edit the division.py
file and add the following code:
## division.py
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
-
Run the script using the python
command:
python ~/project/division.py
You will see an error message similar to this:
Traceback (most recent call last):
File "/home/labex/project/division.py", line 4, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
This error message indicates that a ZeroDivisionError
occurred because we tried to divide by zero. Without exception handling, the program terminates abruptly.
Now, let's use exception handling to handle this error gracefully.
-
Modify the division.py
file to include a try...except
block:
## division.py
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
In this code, the try
block contains the code that might raise an exception. If a ZeroDivisionError
occurs within the try
block, the code in the except
block will be executed.
-
Run the script again:
python ~/project/division.py
Now, instead of crashing, the program will output:
Error: Cannot divide by zero.
This demonstrates the basic structure of exception handling:
- The
try
block encloses the code that might raise an exception.
- The
except
block specifies the type of exception to catch and the code to execute if that exception occurs.
You can also catch multiple types of exceptions using multiple except
blocks:
## division.py
numerator = 10
denominator = "abc"
try:
result = numerator / int(denominator)
print(result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
In this example, we've added a ValueError
exception handler. If the denominator
cannot be converted to an integer (e.g., if it's a string like "abc"), a ValueError
will be raised, and the corresponding except
block will be executed.
Run the script:
python ~/project/division.py
Output:
Error: Invalid input. Please enter a number.
Exception handling allows you to write more robust and user-friendly programs by anticipating and handling potential errors.