1.1.1 Handling Exceptions
Advanced Python concepts extend the foundational knowledge and empower programmers to handle more complex tasks effectively. This section covers key topics such as exception handling, which deals with managing errors gracefully, and file handling, which involves reading from and writing to files. Mastering these concepts is essential for developing robust and efficient Python applications.
Exception Handling
Exception handling is a mechanism to manage errors that occur during program execution. It allows a program to continue running or gracefully terminate if an error occurs, ensuring more robust and error-resilient code.
Try-Except Blocks
In Python, the try block lets you test a block of code for errors, and the except block lets you handle errors if they occur.
Example:
# Input a try:
try:
result = 10 / a # This line creates error if the value of 'a' is 0
except ZeroDivisionError:
print("You can't divide by zero!")
Explanation:
- The try block contains code that might cause an error.
- The except block catches the
ZeroDivisionErrorand handles it by printing a message.
File Handling
File handling involves reading from and writing to files. It is essential for storing data persistently.
Opening, Reading, and Closing Files
To read a file, open it using the open() function, read its contents, and then close the file to free up resources.
# Open and read a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation:
- The
withstatement ensures that the file is properly closed after its suite finishes, even if an error occurs. - The file is opened in read mode (
r), read contents intocontent, and then printed. - The file opened using
withis automatically closed.
Writing to Files
To write to a file, open it in write mode (w) and use the write() method. To append data, use append mode (a).
# Writing to a file
with open("example.txt", "w") as file:
file.write("As-Salaam-Alaikum, World!\n")
# Appending to a file
with open("example.txt", "a") as file:
file.write("Appending new line.\n")
Explanation:
- The file is opened in write mode (
w) to overwrite its contents and write new data. - The file is opened in append mode (
a) to add data without overwriting existing content.