Python Jump Instructions

Watch it together with the written tutorial to deepen your understanding: Raise and Handle Exceptions in Python

In this article, we’ll explore how to handle exceptions in Python using try-except blocks. We’ll also learn about other exception-related keywords like raise, assert, else, and finally. By the end of this guide, you’ll have a solid understanding of how to work with Python exceptions.

First, let’s understand what an exception is and how it differs from a syntax error in Python. An exception occurs when syntactically correct code results in an error. Syntax errors occur when the parser detects an incorrect statement. For example:

# This script is used to demonstrate the concept of exceptions in Python.

# First, let's define what an exception is and how it differs from a syntax error.
# An exception occurs when syntactically correct code results in an error, while syntax errors occur when the parser detects an incorrect statement.

# In this example, the print statement will result in an exception because the variable x has not been defined.
# To fix this, we can either define x or remove the print statement.



# Define the variable x
x = 10

# Print the value of x
print(x)

# Define the variable y and perform a mathematical operation
y = 5 + 8 * 3

# The script will now run without any errors.

In this case, there’s a syntax error because of the extra bracket after ‘*’. The arrow indicates where the parser ran into the syntax error. Additionally, the error message gives you a hint about what went wrong: “ValueError: invalid syntax (, line 2)”

On the other hand, an exception is raised when Python encounters unexpected behavior in your code. For example:

# The following script attempts to convert the string "hello" into an integer, which is not possible and will result in a ValueError.

# To fix this, we can use a try-except block to catch the exception and handle it appropriately.

try: # try block to attempt the conversion
    x = int("hello") # this line will raise a ValueError
except ValueError: # except block to handle the exception
    print("Cannot convert string to integer.") # print a message to inform the user of the error

# The script will now run without any errors, as the exception is caught and handled.

# Output: Cannot convert string to integer.

In this case, there’s no syntax error, but instead a ValueError because ‘hello’ cannot be converted to an integer. The last line of the message indicates what type of exception error you ran into. Instead of just writing “exception error”, Python details what type of exception error it encountered: “ValueError”.

Now that we understand exceptions and how they differ from syntax errors, let’s learn about raising exceptions in Python using the raise keyword. For example:

# Define a function named "divide" that takes in two parameters, x and y
def divide(x, y):
    # Check if the value of y is equal to 0
    if y == 0:
        # If y is equal to 0, raise a ValueError with a custom message
        raise ValueError("Cannot divide by zero")
    # If y is not equal to 0, return the result of x divided by y
    return x / y

In this code snippet, we’re defining a function called ‘divide’. If the second argument (y) is equal to zero, then we’re raising a ValueError with a custom message.

Debugging and testing your code using assert can also be helpful in identifying exceptions. For example:

# Defining a function called 'calculate_sum' that takes in a list of numbers as an argument
def calculate_sum(numbers):
    # Initializing a variable 'total' to store the sum of the numbers
    total = 0
    # Looping through each number in the list
    for num in numbers:
        # Verifying if the number is between 1 and 5 (inclusive)
        assert 1 <= num <= 5, "Number must be between 1 and 5"
        # Adding the number to the total sum
        total += num
    # Returning the total sum
    return total

In this code snippet, we’re defining a function called ‘calculate_sum’. We’re using the assert keyword to verify if each number in the list is between 1 and 5 (inclusive). If an exception occurs due to invalid input or if the file doesn’t exist, then Python will raise an AssertionError.

Handling exceptions with try-except blocks can also be helpful in identifying errors that occur during runtime. For example:

# Define a function to read a file
def read_file(filename):
    try:
        # Open the file and read its contents
        with open(filename, 'r') as f:
            content = f.read() # Read the contents of the file and store it in a variable
    except FileNotFoundError: # Handle the exception if the file is not found
        print("File not found")
    else:
        # Print the contents of the file if no exceptions were raised
        print(content) # Print the contents of the file

# Call the function with a valid filename
read_file("example.txt")

# Call the function with an invalid filename to test the exception handling
read_file("invalid.txt")

In this code snippet, we’re defining a function called ‘read_file’. We’re using a try-except block to handle any FileNotFoundError that may occur when trying to open the specified file. If an exception occurs due to invalid input or if the file doesn’t exist, then Python will print “File not found”.

Fine-tuning your exception handling with else and finally can also be helpful in identifying errors that occur during runtime. For example:

# This function is used to run a command on Linux using the subprocess module
def linux_interaction():
    try:
        # Import the subprocess module to run a command on Linux
        import subprocess
        # Use the check_output method to run the "ls -l" command and store the output in a variable
        output = subprocess.check_output(["ls", "-l"])
        # Print the output of the command
        print("Output:", output)
    # Catch any exceptions that may occur during runtime
    except Exception as e:
        # Print an error message if an exception occurs
        print("An error occurred while running the command:", str(e))
    # If no exceptions were raised during runtime, execute the following code
    else:
        # Print a message indicating that the command was executed successfully
        print("Command executed successfully")
    # Regardless of whether or not an exception was raised, execute the following code
    finally:
        # Print a message indicating that resources are being cleaned up
        print("Cleaning up...")

In this code snippet, we’re defining a function called ‘linux_interaction’. We’re using a try-except block to handle any exceptions that may occur when running the specified command on Linux. If an exception occurs due to invalid input or if the command doesn’t execute successfully, then Python will print “An error occurred while running the command:”.

The else clause is executed only if no exceptions were raised during runtime. In this case, we’re printing a message that indicates that the command executed successfully. The finally clause is always executed regardless of whether or not an exception was raised during runtime. In this case, we’re cleaning up resources using print(“Cleaning up…”).

Creating custom exceptions in Python can also be helpful when you want to raise your own specific type of error that better describes the problem at hand. For example:

# Creating a custom exception class in Python
# This class will be used to raise specific errors related to platform issues

class PlatformException(Exception):
    # This class inherits from the base Exception class
    # It will be used to create custom exceptions for platform-related issues
    
    # The __init__ method is used to initialize the class and its attributes
    # It takes in the self parameter, which refers to the current instance of the class
    # It also takes in the message parameter, which is set to a default value if not provided
    def __init__(self, message="An unexpected platform-related issue occurred."):
        # The self.message attribute is used to store the error message
        self.message = message
    
    # The __str__ method is used to convert the object to a string
    # It takes in the self parameter and returns the string representation of the object
    def __str__(self):
        # The str() function is used to convert the message attribute to a string
        return str(self.message)

In this code snippet, we’re defining a custom exception called ‘PlatformException’. This type of error is raised when an unexpected platform-related issue occurs. We’re using the __init__ method to initialize our custom exception with a message that describes what went wrong. The __str__ method returns a string representation of the custom exception for debugging purposes.

SICORPS