Kodeclik Blog
Python’s try-except block
Python's try-except mechanism is a powerful tool for handling errors and exceptions in your code.
For instance, consider the below code:
print(5/5)
print(5/0)
print(5/1)
The output will be:
1.0
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(5/0)
ZeroDivisionError: division by zero
As can be seen, the first line produces a proper result, i.e., 1. But the second line led to an error, called an “exception”. We get the message that we have reached a “ZeroDivisionError”. Most importantly, the program is aborted and the third print statement is not reached at all.
Python’s try-except block is a way to gracefully handle such potential errors and not cause programs to abort unceremoniously. Here’s how that would work:
def safe_divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"Result: {result}")
safe_divide(5, 5)
safe_divide(5, 0)
safe_divide(5, 1)
The output is:
Result: 1.0
Cannot divide by zero
Result: 5.0
Note that we have replaced the “5/5”, “5/0” etc with safe_divide(5, 5) and safe_divide(5, 0), etc.
This function, safe_divide, takes two parameters, x and y, and attempts to divide x by y. It uses a try-except-else block for error handling. Firs, the try block attempts the division operation. If a ZeroDivisionError occurs (when y is zero), it's caught by the except block, which prints an error message. If no exception occurs, the else block executes, printing the result of the division.
In general, here is a simple template of how to setup a try-except block and when to use it:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
Note that our earlier code works only if the exception is a “ZeroDivisionError”. If you tried using the code like so:
safe_divide("Cake", "2 People")
you will get:
Traceback (most recent call last):
File "main.py", line 13, in <module>
safe_divide("Cake", "2 People")
File "main.py", line 3, in safe_divide
result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
To trap errors of this kind, you will need to expand your try-except block like:
def safe_divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Invalid input type")
else:
print(f"Result: {result}")
safe_divide("Cake", "2 People")
Now the output will be:
Invalid input type
as expected.
There are many other examples of where you will need to use Python try-except blocks. Below are a few of them.
Below is an example that shows how to safely open and read a file, handling potential errors:
def read_file_content(filename):
try:
with open(filename, 'r') as file:
content = file.read()
print(f"File contents:\n{content}")
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except PermissionError:
print(f"Error: You don't have permission to read '{filename}'.")
except IOError as e:
print(f"An I/O error occurred: {str(e)}")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")
# Usage examples
read_file_content("existing_file.txt")
read_file_content("non_existent_file.txt")
This function handles specific file-related exceptions and provides appropriate error messages. It uses a try-except block to catch potential errors such as FileNotFoundError, PermissionError, and IOError, providing specific error messages for each case. This function ensures that common file-related issues are handled gracefully, preventing the program from crashing and giving users clear feedback about what went wrong during the file reading process.
Below is an example demonstrating error handling when parsing JSON data:
import json
def parse_json(json_string):
try:
data = json.loads(json_string)
print("Successfully parsed JSON:")
print(json.dumps(data, indent=2))
except json.JSONDecodeError as e:
print(f"Invalid JSON format: {str(e)}")
except TypeError:
print("Error: Input must be a string")
# Usage examples
parse_json('{"name": "John", "age": 30}')
parse_json('{"name": "John", "age": }') # Invalid JSON
parse_json(123) # Not a string
This example showcases error handling when working with JSON data in Python. It utilizes the json module to parse a JSON string and handles two main types of errors: JSONDecodeError for invalid JSON format and TypeError for non-string inputs. By catching these specific exceptions, the function can provide meaningful error messages to users, making it easier to identify and correct issues with JSON data input, which is crucial in many data processing and API-related tasks.
This example shows how to handle errors when connecting to a database (using a hypothetical database library):
import hypothetical_db_library as db
def connect_to_database(host, username, password):
try:
connection = db.connect(host, username, password)
print("Successfully connected to the database")
return connection
except db.ConnectionError:
print("Error: Unable to connect to the database. Please check your network connection.")
except db.AuthenticationError:
print("Error: Invalid username or password")
except db.DatabaseError as e:
print(f"A database error occurred: {str(e)}")
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")
return None
# Usage example
connection = connect_to_database("localhost", "user", "password")
if connection:
# Perform database operations
connection.close()
This example illustrates error handling in the context of connecting to a database using a hypothetical database library. It demonstrates how to catch and handle various database-related exceptions such as ConnectionError, AuthenticationError, and general DatabaseError. This approach allows the function to provide specific feedback for different types of connection issues, such as network problems or invalid credentials, enhancing the user experience and making database interactions more reliable and informative in applications that require database access.
In summary, try-except blocks can be used to handle different types of errors in various scenarios, making your code more robust and user-friendly. They show the importance of catching specific exceptions before general ones and providing informative error messages to users or logging systems.
Want to learn Python with us? Sign up for 1:1 or small group classes.