Exception Handling for Writing Safe Code
While programming, unexpected errors or issues can arise.
To prevent your program from terminating abruptly and to handle such situations appropriately, exception handling is necessary.
In this lesson, we will explore the concept of exceptions and how to handle them in Python.
What are exceptions in programming?
In programming, an Exception
refers to unexpected events or errors that occur during the execution of code.
For example, trying to open a non-existent file or attempting to convert a non-numeric value to a number can raise exceptions.
When such exceptions occur, the program immediately stops executing, and the following code does not run.
Thus, it is important to handle exceptions to prevent these errors or to deal with them appropriately when they occur.
Handling exceptions in Python
In Python, exceptions are handled using the try
, except
, and finally
statements.
Basic structure for handling exceptions: try and except
Write the code that might cause an exception in a try
block, and handle the exception in the except
block.
If an exception occurs, the remaining code in the try
block is skipped and execution jumps to the except
block.
try:
# Prompt the user to enter a number and convert it to an integer
number = int(input("Please enter a number: "))
# Divide 10 by the entered number and store the result in the result variable
result = 10 / number
# Print the result
print(f"Result: {result}")
# A ValueError exception occurs if the user enters a non-numeric value
except ValueError:
# Message printed when a non-numeric value is entered
print("Please enter a valid number")
# A ZeroDivisionError exception occurs if the user enters zero
except ZeroDivisionError:
# Message printed when zero is entered
print("Cannot divide by zero")
In the code above, a ValueError
occurs if the user enters a non-numeric value, and a ZeroDivisionError
occurs if they enter zero.
Each exception is handled in the except
blocks to ensure the program does not terminate prematurely.
Code that always executes: finally
The finally
block contains code that always executes regardless of whether an exception occurs.
This block is used to perform tasks such as closing files or releasing resources that need to be executed at the end of the program.
try:
# Open the example.txt file in read mode
file = open("example.txt", "r")
content = file.read()
print(content)
# A FileNotFoundError exception occurs if the file is not found
except FileNotFoundError:
print("File not found")
# The file is closed regardless of whether an exception occurs
finally:
file.close()
print("File is closed")
In the code example above, if the file does not exist, a FileNotFoundError
is raised. Nonetheless, the finally
block ensures the file is closed even if an exception occurs.
This usage of finally
is for conducting cleanup operations at the end of the code execution.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.